gpt4 book ai didi

javascript - 使用拼接进行数组操作

转载 作者:行者123 更新时间:2023-11-28 17:33:36 25 4
gpt4 key购买 nike

我有这个数组两个函数,一个添加到它,另一个删除它,或者至少这就是计划。有人可以看看我的代码并看看我的第二个函数有什么问题吗? splice 正在获取数组中的最后一个元素,但不是要获取的特定元素。请

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);
}

关于javascript - 使用拼接进行数组操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49664143/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com