简体   繁体   English

将字长存储在javascript数组中

[英]Storing the word length in javascript array

I am puzzled as to why I can not store the word length in a javascript array. 我对为什么不能将字长存储在javascript数组中感到困惑。

I have tried 我努力了

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

but both aren't accepted in javascript. 但两者都不被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. 来自MDN :作为Array类型实例的对象的length属性设置或返回该数组中元素的数量。 The value is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array. 该值是一个无符号的32位整数 ,在数值上总是大于数组中的最高索引。

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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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