简体   繁体   中英

jQuery $.each push(this) does not work correctly

Actualy i'd like to create a simple array resort.

var preSelected = "13_335 14_555";
var arrayClasses = preSelected.split(' ');
var arrayClassesSorted = new Array();

$.each(arrayClasses, function() {
//var elCount = $("li."+ this).size();
elCount = 20 ...... ;
arrayClassesSorted[elCount] = this;
    ....
});

The result should be a array looks like this (counter doesnt work without the li Classes...):

Array (
  [20] => 14_555
)

But the result i get is this:

[20] => Array
    (
        [0] => 1
        [1] => 4
        [2] => _
        [3] => 5
        [4] => 5
        [5] => 5
)

And now i'd like to kow, why "this" creates a second dimension to this array.

If put this into String(this), its work. But is this realy the desired result for "this" in this case?

I think this is just what the console shows you, it does not actually mean that you have a two-dimensional array. Don't take everything you see as truth.

You are assigning a string object instead of a string primitive and the console treats the object as array-like object, because it has a .length and numerical properties.

Here is what the Chrome console prints for a string object and a string primitive:

> console.log(new String('foo'));
  String {0: "f", 1: "o", 2: "o"}
  undefined
> console.log('foo');
  foo
  undefined

You should always avoid string objects, since they can lead to unexpected behaviour:

> new String('foo') === 'foo'
  false

Better assign the primitive value:

$.each(arrayClasses, function(val) {
    //var elCount = $("li."+ this).size();
    elCount = 20 ...... ;
    arrayClassesSorted[elCount] = val;
    ....
});

"Where does the string object come from?" you might ask.

You are assigning this to the array:

arrayClassesSorted[elCount] = this;

and this will always be an object (primitive values are converted to objects), unless the function runs in strict mode [MDN] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM