我在每个循环中都有一个循环:
var data_array = [];
$('td.form').each(function(){
$(this).children('input[type=hidden]').each(function(index, element){
var name = $(element).attr('name');
data_array[index] = $(element).val();
});
console.log(data_array);
});
第一个循环遍历特定的表格单元格,其中包含一组隐藏的输入。
我设法将隐藏输入的数据收集到数组中。当我在每次迭代时写入控制台时,我得到了这个:
[id: "56a8382bd5b88", date: "Tuesday, February 16th, 2016 - 10:00 PM UTC", waiting_list: "false"]
[id: "56a9260e14b3e", date: "Tuesday, February 23rd, 2016 - 5:00 PM UTC", waiting_list: "true"]
我想要做的是将这些数组写入一个新的数组或对象中,以便稍后在脚本中使用这样的内容:
myNewArray = [
first = [ /* 'first' as placeholder text */
id: "56a8382bd5b88",
date: "Tuesday, February 16th, 2016 - 10:00 PM UTC",
waiting_list: "false"
],
second = [ /* 'second' as placeholder text */
id: "56a9260e14b3e",
date: "Tuesday, February 23rd, 2016 - 5:00 PM UTC",
waiting_list: "true"
]
]
我一直在尝试创建一个新数组并使用push:
var data_array = [];
var myOtherNewArray = [];
$('td.form').each(function(){
$(this).children('input[type=hidden]').each(function(index, element){
var name = $(element).attr('name');
data_array[index] = $(element).val();
});
console.log(data_array);
myOtherNewArray.push(data_array);
});
console.log(myOtherNewArray);
但这不断给我不必要的重复:
myOtherNewArray = [
first = [
id: "56a9260e14b3e",
date: "Tuesday, February 23rd, 2016 - 5:00 PM UTC",
waiting_list: "true"
],
second = [
id: "56a9260e14b3e",
date: "Tuesday, February 23rd, 2016 - 5:00 PM UTC",
waiting_list: "true"
]
]
显然我在覆盖循环中的数据。我似乎无法在这里找出正确的构造。任何帮助将不胜感激!
答案 0 :(得分:-1)
这是我对JavaScript Array原型进行的一些扩展的片段...我希望它能帮到你。它是一个Array.contains(item,[property])函数。
//returns boolean showing whether array contains an item, or if one of its
//properties (arr[i].prop) is equal to item
Array.prototype.contains = function (item, prop) {
var arr = this;
if (prop == undefined || prop == null) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] == item) {
return true;
}
}
}
else {
for (var i = 0; i < arr.length; i++) {
if (arr[i][prop] == item) return true;
}
}
return false;
}
有了这个,我相信你可以检查数组是否包含一个原始对象,或一个具有特定值属性的对象。
如果你想检查数组是否包含数字5,Array.indexOf(5)可以轻松处理,
var arr = [1,2,3,4,5];
console.log(arr.indexOf(5));
但是,如果您想检查数组是否包含具有属性的对象
var arr = [{name: "john", age: 11},{name: "paul", age: 11}];
console.log(arr.contains("paul", "name"));
这将打印到控制台。
编辑:为了确保数组不包含重复值,您需要一个属性作为键,在您的情况下,我认为是属性“id” 因此,在遍历数组时,检查结果数组是否包含“id”值与迭代项相同的项。