如何在javascript中将关联项推送到数组?

时间:2022-08-26 14:11:27

Please correct this code:

请更正此代码:

var arr = [];
var name = "name";
var val = 2;
arr.push(val); //works , but not associative
arr[name] = val; //does not work
console.log(arr);

jsfiddle

的jsfiddle

4 个解决方案

#1


90  

To make something like associative array in JavaScript you have to use objects. ​

要在JavaScript中创建类似关联数组的东西,您必须使用对象。

var arr = {}; // {} will create an object
var name = "name";
var val = 2;
arr[name] = val;
console.log(arr);​

DEMO: http://jsfiddle.net/bz8pK/1/

演示:http://jsfiddle.net/bz8pK/1/

#2


20  

JavaScript doesn't have associate arrays. You need to use Objects instead:

JavaScript没有关联数组。您需要使用对象:

var obj = {};
var name = "name";
var val = 2;
obj[name] = val;
console.log(obj);​

To get value you can use now different ways:

为了获得价值,您现在可以使用不同的方式:

console.log(obj.name);​
console.log(obj[name]);​
console.log(obj["name"]);​

#3


7  

Javascript has associative arrays. Here is a working snippet.

Javascript具有关联数组。这是一个工作片段。

<script type="text/javascript">
  var myArray = [];
  myArray['thank'] = 'you';
  myArray['no'] = 'problem';
  console.log(myArray);
</script>

They are simply called objects.

它们简称为对象。

#4


0  

This is how you create an associative array

这是您创建关联数组的方法

var arr = [];    
var name = "name";
var val = 'some value';
var val2 = 'some other value';

arr[name] = new Array(val);
arr[name].push(val2)
console.log(arr);

You may find here more useful information about javascript arrays

您可以在这里找到有关javascript数组的更多有用信息

#1


90  

To make something like associative array in JavaScript you have to use objects. ​

要在JavaScript中创建类似关联数组的东西,您必须使用对象。

var arr = {}; // {} will create an object
var name = "name";
var val = 2;
arr[name] = val;
console.log(arr);​

DEMO: http://jsfiddle.net/bz8pK/1/

演示:http://jsfiddle.net/bz8pK/1/

#2


20  

JavaScript doesn't have associate arrays. You need to use Objects instead:

JavaScript没有关联数组。您需要使用对象:

var obj = {};
var name = "name";
var val = 2;
obj[name] = val;
console.log(obj);​

To get value you can use now different ways:

为了获得价值,您现在可以使用不同的方式:

console.log(obj.name);​
console.log(obj[name]);​
console.log(obj["name"]);​

#3


7  

Javascript has associative arrays. Here is a working snippet.

Javascript具有关联数组。这是一个工作片段。

<script type="text/javascript">
  var myArray = [];
  myArray['thank'] = 'you';
  myArray['no'] = 'problem';
  console.log(myArray);
</script>

They are simply called objects.

它们简称为对象。

#4


0  

This is how you create an associative array

这是您创建关联数组的方法

var arr = [];    
var name = "name";
var val = 'some value';
var val2 = 'some other value';

arr[name] = new Array(val);
arr[name].push(val2)
console.log(arr);

You may find here more useful information about javascript arrays

您可以在这里找到有关javascript数组的更多有用信息