Javascript 带拼接的阵列操作
我有两个函数,一个添加到数组中,另一个从数组中删除,或者至少这是计划。有人能看看我的代码,看看我的第二个函数有什么问题吗。splice正在获取数组中的最后一个元素,但不是我试图获取的特定元素。请Javascript 带拼接的阵列操作,javascript,Javascript,我有两个函数,一个添加到数组中,另一个从数组中删除,或者至少这是计划。有人能看看我的代码,看看我的第二个函数有什么问题吗。splice正在获取数组中的最后一个元素,但不是我试图获取的特定元素。请 var shoppingCart = []; function AddtoCart(name, description, price) { // JavaScript Object that holds three properties : Name,Description and Pric
var shoppingCart = [];
function AddtoCart(name, description, price) {
// JavaScript Object that holds three properties : Name,Description and Price
var singleProduct = {};
//Fill the product object with data
singleProduct.Name = name;
singleProduct.Description = description;
singleProduct.Price = price;
//Add newly created product to our shopping cart
shoppingCart.push(singleProduct);
//call display function to show on screen
}
function removefromCart(name, description, price) {
// JavaScript Object that will hold three properties : Name,Description and Price
var singleProduct = {};
//Fill the product object with data
singleProduct.Name = name;
singleProduct.Description = description;
singleProduct.Price = price;
var index = shoppingCart.indexOf(singleProduct);
shoppingCart.splice(index, 1);
}
在
removefromCart
内部,singleProduct
是一个新创建的对象,因此它肯定不会存在于shoppingCart
中,即使它具有相同的属性-非原语变量(如对象)基本上指向内存位置,因此如果创建新对象,指向该对象的变量有一个新的内存位置,脚本中的其他变量都不知道,因此anyArr.indexOf(newObject)
将始终返回-1
改用.findIndex
:
function removefromCart(name, description, price) {
const index = shoppingCart.findIndex(({ Name, Description, Price }) => (
name === Name &&
description === Description &&
price === Price
));
if (index === -1) {
console.log('No matching product found!');
return;
}
shoppingCart.splice(index, 1);
}
在
removefromCart
内部,singleProduct
是一个新创建的对象,因此它肯定不会存在于shoppingCart
中,即使它具有相同的属性-非原语变量(如对象)基本上指向内存位置,因此如果创建新对象,指向该对象的变量有一个新的内存位置,脚本中的其他变量都不知道,因此anyArr.indexOf(newObject)
将始终返回-1
改用.findIndex
:
function removefromCart(name, description, price) {
const index = shoppingCart.findIndex(({ Name, Description, Price }) => (
name === Name &&
description === Description &&
price === Price
));
if (index === -1) {
console.log('No matching product found!');
return;
}
shoppingCart.splice(index, 1);
}
只是一个想法@joel记住建议的解决方案使用ES6表示法,这样您可能会在使用旧浏览器或类似IE时遇到一些问题。您当然可以使用
function(){…}
如果需要,请不要使用委派
。为了方便和代码可读性,请始终使用ES6+编写-如果您需要支持IE11和其他古老的浏览器,请使用Babel,这正是它的目的。只是一个想法@joel请记住建议的解决方案使用ES6表示法,这样您可能会在较旧的浏览器或IE中遇到一些问题。您当然可以使用function(){…}
如果需要,请不要使用委托
。始终使用ES6+编写,以方便使用和代码可读性-如果您需要支持IE11和其他古老的浏览器,请使用Babel,这正是它的用途。