简体   繁体   中英

Storing the word length in javascript array

I am puzzled as to why I can not store the word length in a javascript array.

I have tried

var i = [];
i["length"] = "ABC";
i["len"+"gth"] = "ABC";

but both aren't accepted in javascript. Can anyone explain it, and is there a way that I can store the word length in an array as above.

Since some asked for more detail. I am creating a list of words that I need to do a lookup at and find the value to display to the user. My list contains for example:

localVars.FunctionDic = [];
localVars.FunctionDic["lastindexof"] = "LastIndexOf(text, textToLocate)";
localVars.FunctionDic["specificindexof"] = "SpecificIndexOf(text, textToLocate, indexNumber)";
localVars.FunctionDic["empty"] = "Empty(text)";
localVars.FunctionDic["length"] = "Length(text)";

everything works except for the "length"

and I am using an array since I need to test if the word a user search for is in my array, and if it is display the value, if it is not, show nothing

It does not work because you are trying to write a string to a property that only allows a number.

From MDN : The length property of an object which is an instance of type Array sets or returns the number of elements in that array. The value is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array.

With the limited details in your question it is hard to tell what you are actually trying to accomplish. It seems like you want to use an array like an object. If that is the case, use an object.

var i = {};
i["length"] = "ABC";

Based on the expected output, I believe you should be using an object not an array.

 const FunctionDic = { lastindexof: "LastIndexOf(text, textToLocate)", specificindexof: "SpecificIndexOf(text, textToLocate, indexNumber)", empty: "Empty(text)", length: "Length(text)", }; console.log(FunctionDic["lastindexof"]); console.log(FunctionDic["specificindexof"]); console.log(FunctionDic["empty"]); console.log(FunctionDic["length"]); 

To store the word length in an array you can do:

var i = ["length"]

If you want to store the length of a word in an array you can do:

var lengthOfHello = "hello".length
var i = [lengthOfHello]

 var i = ["ABC"]; console.log(new Array(i[0].length).length); 

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