简体   繁体   中英

Accessing JavaScript array strings using jquery each method

I would like to access Java Script string elements (within an array) via jquery. I have written simple method that simulates what I am trying to do. This method causes RangeError exception.

function test() {
    var arr = ["janusz", "renia"];
    $(arr).each(function () {
        var  el = $(this).text();
        console.log(el);
    });
}

The error in the console looks like this:

jquery.js:1602 Uncaught RangeError: Maximum call stack size exceeded
    at Sizzle.getText (jquery.js:1602)
    at Sizzle.getText (jquery.js:1610)
    at Sizzle.getText (jquery.js:1610)
    at Sizzle.getText (jquery.js:1610)
    at Sizzle.getText (jquery.js:1610)
    at Sizzle.getText (jquery.js:1610)
    at Sizzle.getText (jquery.js:1610)
    at Sizzle.getText (jquery.js:1610)
    at Sizzle.getText (jquery.js:1610)
    at Sizzle.getText (jquery.js:1610)
…

Why can't I access the string via 'this' object inside each method?

.text() is meant for retrieving text from an element . You don't have any DOM elements here, only a plain array composed of strings.

The error is thrown because getText (which jQuery calls when trying to get the text of an element) does

getText = Sizzle.getText = function( elem ) {
    var node,
        ret = "",
        i = 0,
        nodeType = elem.nodeType;

    if ( !nodeType ) {
        // If no nodeType, this is expected to be an array
        while ( (node = elem[i++]) ) {
            // Do not traverse comment nodes
            ret += getText( node );
        }
    }

resulting in infinite recursion.

While you can just refer to this in strict mode to have it refer to the string being iterated over...

 'use strict'; var arr = ["janusz", "renia"]; $(arr).each(function() { console.log(this); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

It'd be far easier to ditch jQuery entirely and use plain JavaScript.

 var arr = ["janusz", "renia"]; for (const item of arr) { console.log(item); }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>

or

 var arr = ["janusz", "renia"]; arr.forEach((item) => { console.log(item); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>

or

 var arr = ["janusz", "renia"]; for (let i = 0; i < arr.length; i++) { console.log(arr[i]); }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>

If you're new to programming, I'd personally recommend only using jQuery when you need to, and not trying to use it for absolutely everything (which is an unfortunately common paradigm).

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