将对象中的所有值推送到数组中?

3
我刚开始学习编程。有人能帮我解决这个问题吗?我目前只有以下代码:
var myArr = [];
for (var k in input) {
    myArr.push(

我在正确的道路上吗?

编写一个循环将对象中的所有值推送到数组中。

input: {two: 2, four: 4, three: 3, twelve: 12}
output: [2, 4, 3, 12]

你,你走在正确的轨道上,只需将 input[k] 推到数组中。 - adeneo
检查 hasOwnProperty - user1950929
在现代的ES5代码中,这几乎是不必要的。jQuery可以完美地运行而不需要它... - Alnitak
7个回答

2

不使用循环:

const input = {two: 2, four: 4, three: 3, twelve: 12};
const myArr = Object.values(input);
console.log(myArr);
// output: [2, 4, 3, 12]


1

1
如果您使用JavaScript原生语言编写,可以使用push()函数:
例如:
var persons = {roy: 30, rory:40, max:50};

var array = [];

// push all person values into array
for (var element in persons) {
    array.push(persons[element]);
}

好运!


0

var myArr = []; 

var input = {two: 2, four: 4, three: 3, twelve: 12};

for (var k in input) { 
    myArr.push(input[k]);
}
alert(myArr);


0

data.input[k] 是你想要的

var data = {input: {two: 2, four: 4, three: 3, twelve: 12}}, myArr = [];

for(k in data.input) myArr.push(data.input[k]);

0

使用underscore.js

var myArr = _.values(input);

这是一个非常有用的库,gzip 压缩后只有 5.3k


0
在每次 for in 循环的迭代中,变量 k 会被赋值为对象 input 中的下一个属性名,因此您需要推入 input[k]。如果对象具有其原型的属性,并且您只想将对象自己的属性推入数组(这可能是您想要做的),则应使用 hasOwnProperty
var input: {two: 2, four: 4, three: 3, twelve: 12}
var myArr = [];
for (var k in input) {
//  if( input.hasOwnProperty( k) ) { //not necessary
    myArr.push( input[k] );
//  } 
}

请注意,for in循环以任意顺序遍历对象,即数组中项目的顺序可能与您预期的不同。

另请参阅:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

编辑:正如Alnitak在对OP的评论中提到的那样,现在可能不必使用hasOwnPropery()


.hasOwnProperty 是不必要的。任何人如果在不安全的 ES5 方式(通过 Object.defineProperty)扩展 Object.prototype 而不使扩展变为不可枚举,那么他们应该自行承担后果。 - Alnitak

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接