admin管理员组

文章数量:1326278

In my mind I want to push a key-value on array.

Say for example in PHP this is done like this:

$err = array();
function check($k,$v) {
  $err[$k] = $v; 
}

How is this done exactly in JavaScript/jQuery?

In my mind I want to push a key-value on array.

Say for example in PHP this is done like this:

$err = array();
function check($k,$v) {
  $err[$k] = $v; 
}

How is this done exactly in JavaScript/jQuery?

Share Improve this question asked May 7, 2012 at 8:44 planet xplanet x 1,6175 gold badges27 silver badges44 bronze badges 1
  • @FelixKling - any string send as parameter – planet x Commented May 7, 2012 at 8:50
Add a ment  | 

2 Answers 2

Reset to default 6

Javascript key/value pair support in Object, not in Array

Insert Element:

var arr= [1,2,3],
    result = {};

for(var key in arr) {
   result[key] = arr[key]; // in this case key will be 0,1,2 i.e index of array element
}

Check that a key exists:

function checking(k, v) {
  if(result.k != null || result.k !=  undefined) {
    // do something
  }
}

According to your function:

var err = {}; // not array, should be object
function check(k,v) {
  err[k] = v; // or err.k = v;
}

More on insert:

var x = [];

x.some = 'some'; // OK; arrays are objects
x['some'] = 'some'; // exactly the same

Get value:

x.home; // give 'some'
x['home']; // give 'some'

Count length:

If you want to get length of an array you have to use .length.

For example:

x.length; // will return 1

And if you want to count the length of an Object:

var obj = {a: 'XYZ', b: 'PQR'};

Object.keys(obj).length; // will return 2

To Delete item:

if you want to remove an item from an Object:

delete obj[key];

to delete an item from an array:

delete arr[index]; // index is position of the element within array

also to remove array element you can do

arr.splice(0,2); // splice(index, howmany, [item1, item2, ...., itemx])
                 // in this example from start 2 items will delete

You use an object. And do it in much the same way.

var $err = {};
function check($k, $v) {
     $err[$k] = $v;
}

Granted, that's not an array though.

Do take note that you can actually do this in Javascript arrays, and the interpreter will let you.

var $err = []; // an array
function check($k, $v) {
    $err[$k] = $v;
}

But you're not really pushing to the array, but rather extending the array object. You can check this out with this:

var foo = [];
foo['hello'] = 'world';

console.log(foo);            // []
console.log(foo['hello']);   // 'world'
console.log(foo.hello);      // 'world'
console.log(foo.length);     // 0

... so best to watch out for this gotcha. :D

本文标签: phpjavascript push key valueStack Overflow