javascript 不循环获取对象值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16731174/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 05:46:54  来源:igfitidea点击:

Get object values without looping

javascriptjqueryobject

提问by hsz

I have following object:

我有以下对象:

var input = {
  'foo': 2,
  'bar': 6,
  'baz': 4
};

Is it possible to get values from this object without looping it ?

是否可以在不循环的情况下从此对象获取值?

It is possible to use jQuery.

可以使用jQuery.

Expected result:

预期结果:

var output = [2, 6, 4];

采纳答案by Mohammad Adil

var arr = $.map(input,function(v){
 return v;
});

Demo -->http://jsfiddle.net/CPM4M/

演示-->http://jsfiddle.net/CPM4M/

回答by Ja?ck

This is simply not possible without a loop. There's no Object.values()method (yet) to complement Object.keys().

如果没有循环,这是不可能的。没有Object.values()方法(还)来补充Object.keys().

Until then you're basically "stuck" with the below construct:

在那之前,您基本上“卡住”了以下结构:

var values = [];

for (var k in input) {
  if (input.hasOwnProperty(k)) {
    values.push(input[k]);
  }
}

Or, in modern browsers (but of course still using a loop and an anonymous function call):

或者,在现代浏览器中(但当然仍然使用循环和匿名函数调用):

var values = Object.getOwnPropertyNames(input).map(function(key) {
    return input[key];
});

回答by pala?н

You can get values from this object without looping using Object.values()method like:

您可以使用以下Object.values()方法从该对象中获取值而无需循环:

var output = Object.values( input );
console.log( output );  // [2, 6, 4]

DEMO:

演示:

var input = {
  'foo': 2,
  'bar': 6,
  'baz': 4
};

var output = Object.values( input );
console.log( output );

PLEASE NOTE:

请注意:

This is an experimental technology

Because this technology's specification has not stabilized, check the compatibility tablefor usage in various browsers. Also note that the syntax and behavior of an experimental technology is subject to change in future versions of browsers as the specification changes.

这是一项实验技术

由于此技术的规范尚未稳定,请查看兼容性表以了解在各种浏览器中的使用情况。另请注意,随着规范的变化,实验技术的语法和行为可能会在未来版本的浏览器中发生变化。

So, currently it supports Chrome & Firefox only.

因此,目前它仅支持 Chrome 和 Firefox。

回答by rab

I don't know why you want without loop . here my solution

我不知道你为什么想要 without loop 。这是我的解决方案

JSON.stringify( input ).replace(/"(.*?)"\:|\{|\}/g,'' ).split(',')

it print [2, 6, 4]. I didn't test for other json values

它打印[2, 6, 4]。我没有测试其他 json 值

回答by Manish Jangir

var input = {
  'foo': 2,
  'bar': 6,
  'baz': 4
};
var newArr = new Array;
$.each(input,function(key,value) {
    newArr.push(value);
});
alert(newArr)