gpt4 book ai didi

Javascript 将 2 个对象添加到数组中,而不是 1 个。一种是未定义的

转载 作者:行者123 更新时间:2023-11-28 15:33:00 26 4
gpt4 key购买 nike

我正在整理一个购物篮,首先我要实现添加项目位。

但是,由于某种原因,当它将值推送到数组时,它会创建 2 个对象,而它应该只将 1 个对象推送到数组。我不明白为什么!它将数据作为一个对象发送到数组,然后另一个对象的值未定义。

JS

//Create object for everything to run in as this reduces namespace problems if I add anything later
var shop = {};

//Items table
shop.output = document.getElementById('output');

//Create array for items to be stored
shop.items = [];

//Constructor for items
shop.addItem = function(title, description, price) {
'use strict';
this.title = title;
this.description = description;
this.price = price;
//Adds values from contructor to array
shop.addToArray(title, description, price)
}

shop.addToArray = function (t,d,p) {
'use strict';
var item = {title: t, description: d, price: p};
shop.items.push(item);
}


shop.addToTable = function() {
'use strict';
for (var i = 0; i < shop.items.length; i++){
shop.output.innerHTML += '<tr><td>' + shop.items[i].title + '</td><td>' + shop.items[i].description + '</td><td>' + shop.items[i].price + '</td><tr>';
}
}

shop.process = function() {
'use strict';
var title = document.getElementById('title').value;
var description = document.getElementById('description').value;
var price = document.getElementById('price').value;
//send item to constructor
var user = new shop.addItem (title, description, price);
shop.addItem()
console.log(shop.items);
shop.addToTable()
}



function init() {
'use strict';
//Add event listeners for when user clicks add item
document.getElementById("addItemBtn").addEventListener("click", shop.process);

} // End of init() function.
//On window load call init function
window.onload = init;

HTML

<html>
<head>
<meta charset="UTF-8">
<title>Shopping Basket</title>
</head>
<body>

<div id="input">
<form action="#" method="post" id="additem" class="basic-grey">
<label for="title">
<span>Title:</span>
<input type="text" name="title" id="title" required>
</label>
<label for="description">
<span>Name:</span>
<input type="text" name="description" id="description" required>
</label>
<label for="price">
<span>Price: £</span>
<input type="text" name="price" id="price" required>
</label>
<label for="submit" align="center">
<input type="button" value="Add Item!" id="addItemBtn" class="btn blue">
</label>
</form>
</div>

<div id="items" align="center">
<table id="output" class="table">
<th>Item</th>
<th>Description</th>
<th>Price £</th>
</table>
</div>

<script src="js/app.js"></script>
</body>
</html>

最佳答案

问题是这样的:

var user = new shop.addItem (title, description, price);
shop.addItem()

这会调用 shop.addItem() 两次:一次作为构造函数,使用参数 titledescriptorprice ,第二次作为不带参数的普通方法。这是第二次调用,插入一个空项(因为所有参数都未定义)。

关于Javascript 将 2 个对象添加到数组中,而不是 1 个。一种是未定义的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26509525/

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