iHaveTooLearn_ImSoSorry iHaveTooLearn_ImSoSorry - 1 year ago 35
Javascript Question

convert array to jquery ids

Hi im trying to convert my Array with ids in an array with #id.
But i only get one return and i dont know why? I am 100% that im not using the return statement right but i cant get it work

function convortToJquery(e) {

for(var i = 0;i <= e.length;i++){
var jqueryArray = [];

if(!e[i]){
return jqueryArray;
}else{
jqueryArray = "#"+e[i];
}
}
}


EDIT:

var jArrayText = convortToJquery(textWord);

Answer Source

Assuming textWord is an array of strings, your function is creating a new array for every entry. You only want to create a new array once. Also strongly recommend not using the pattern of going past the end of the array and relyingon !e[i] to decide to return from the function. There's no need for that kind of thing, and it introduces a maintenance issue by being odd.

Minimal fixes to your code would look like this (but keep reading):

function convortToJquery(e) {
    var jqueryArray = [];                   // Do this once at the beginning
    for (var i = 0; i < e.length; i++) {    // <, not <=
        jqueryArray[i] = "#" + e[i];        // Put the entry in the array
    }
    return jqueryArray;
}

But: This is exactly what Array#map is for:

function convortToJquery(array) {
    return array.map(function(entry) {
        return "#" + entry;
    });
}

map calls the callback you give it once for each entry in the array, building a new array from what the callback returns.

In an ES2015+ environment (or with transpiling), it's rather more concise:

function convortToJquery(array) {
    return array.map(e => "#" + e);
}

Or if you can use const (or let) and a function expression instead of a full-on function function (which has things this doesn't need):

const convortToJquery = array => array.map(e => "#" + e);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download