2017-11-11 118 views
3

所以我仍然在学习数组和对象,而且我有点卡住了。 我做对象数组的一个例子:Object.keys,切片和拼接

var something = {candy:[{name:"snickers", price:2}, 
        {name:"bounty", price:3}, 
        {name:"mars", price:4}]}; 

Object.keys(something.candy).filter(function(obj){ 
return console.log(something.candy[obj].name); 
}) 

1的问题 - 为什么不,当我写:

var candy1 = Object.keys(something.candy); 
candy1.filter(function(obj){ 
return console.log(obj.name); 
}); 

是不是几乎相同的工作代码意义如上?

2.问题切片如何工作和拼接不?

Object.keys(something.candy).filter(function(obj){ 
return console.log(something.candy[obj].name.slice(0,3)); 
}) 

Object.keys(something.candy).filter(function(obj){ 
return a(something.candy[obj].name.splice(1,3)); 
}) 
+4

'something.candy'已经是一个数组。不要使用'Object.keys',直接使用filter:'something.candy.filter(function(obj){obj.name;})'。 –

+0

'切片'工作,因为有一个函数'String.prototype.slice'和'splice'不会因为没有函数'String.prototype.splice'。因为'name'是一个字符串。只有数组有“拼接”。 –

+0

我现在得到它非常感谢你! @ibrahimmahrir – Eleven11

回答

2

将这些东西拉开并在学习时看看它是有帮助的。例如你有一个对象:

var something = {candy:[{name:"snickers", price:2}, 
 
       {name:"bounty", price:3}, 
 
       {name:"mars", price:4}]}; 
 

 
// what is something.candy: 
 

 
console.log("candy:", something.candy) 
 

 
// an array -- so what do you get with Object.keys? 
 

 
var candy1 = Object.keys(something.candy) 
 
console.log("keys:", candy1) 
 

 
// just the indexes! 
 

 
// So when you try to filter 
 
candy1.filter(function(obj){ 
 
    // there is no obj.name becuase each object is just a number 
 
    return console.log(obj); 
 
});

我想你想只是这样做:

var something = {candy:[{name:"snickers", price:2}, 
 
        {name:"bounty", price:3}, 
 
        {name:"mars", price:4}]}; 
 

 
var select = something.candy.filter(obj => { 
 
    console.log(obj.name) // look at them all 
 
    return obj.name === "mars" // just pick this one 
 
}) 
 

 
console.log("filtered: ", select)

+0

这是很好的解释,谢谢! – Eleven11