所以我有这个数组,我想用那些在运动中具有游泳价值的对象制作一个新的数组。
var watchesArray = [
{
model: "Swim",
image:"",
price: 149.99,
sports:["Swimming", "Running"]
},
{
model: "FR 10",
image:"",
price: 129.99,
sports:["Running"]
},
{
model: "FR 15",
image:"",
price: 199.99,
sports:["Running"]
},
];
到目前为止,我已经有了这个,但是我不知道如何在for循环中每次添加到切片数组上。我应该怎么做?
for (var i = 0; i < watchesArrayLength; i++) {
if (watchesArray[i].sports.indexOf("Swimming") > -1) {
var runningWatchArray = watchesArray.slice(i);
}
}
最佳答案
您可以使用.filter()方法:
watchesArray = [...];
var result = watchesArray.filter(function(watch) {
return watch.sports.indexOf('Swimming') !== -1;
});