JavaScript foreach Key Value数组

时间:2015-09-07 07:45:40

标签: javascript jquery

我只有这个数组:

var sArray = {856:"users", 857:"avatars", 858:"emails"};

我希望以某种方式使用forEach来获取密钥和值:

key = 856
value = user

我的$.each代码没有返回我期望的结果,而是改为:

856:user

我必须与:分开才能获得此数组的键和值。

我的代码是:

$.each(template_array, function(key, value) {
    console.log("key: " + "value: " + value);
});

如何在不分开的情况下访问密钥和值?

4 个答案:

答案 0 :(得分:0)

只需使用+

连接它们



var template_array = {
  856: 'users',
  857: 'avatars',
  858: 'emails'
};
$.each(template_array, function(key, value) {
  console.log('key:' + key + ', value:' + value);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

更新: 我认为你有一个数组然后使用以下代码

&#13;
&#13;
var template_array = ['856: users',
  '857: avatars',
  '858: emails'
];

template_array.forEach(function(v) {
  v = v.split(':');
  console.log('key:' + v[0] + ', value:' + v[1]);
});
&#13;
&#13;
&#13;

答案 1 :(得分:0)

只需使用puntenApp.config(function ($routeProvider) { $routeProvider .when('/pb', { templateUrl : 'js/pages/pb.html', controller : 'pbController' }) .when('/login', { templateUrl : 'js/pages/Login.html', controller : 'configuratieController' }); }); 获取密钥,然后Object.keys获取普通Javascript中的值。

&#13;
&#13;
Array.prototype.forEach
&#13;
&#13;
&#13;

答案 2 :(得分:0)

尝试这个

var template_array = {
   856: 'users',
   857: 'avatars',
   858: 'emails'
};
var date = [];
$.each(template_array,function (key , val){ 
   date.push({key:key, value:val})
 });

console.log(date)

答案 3 :(得分:0)

var template_array = {
  856: 'users',
  857: 'avatars',
  858: 'emails'
};
for (key in template_array) {
  console.log('key:' + key + ', value:' + template_array[key]);
});

相关问题