简体   繁体   English

有没有办法使用第一个数组作为 Javascript 中的参考在第二个数组中获取相应的索引值?

[英]Is there a way to get corresponding index value in a 2nd array using the 1st array as a reference in Javascript?

I am very new to algorithm and programming in general.一般来说,我对算法和编程非常陌生。 I may require more explanation than an average fellow.我可能需要比一般人更多的解释。 Apologies in advance.提前致歉。

My aim is to Create a function that returns a number, based on the string provided.我的目标是根据提供的字符串创建一个返回数字的 function。 I have been told that this can be done using loops.有人告诉我这可以使用循环来完成。 I believe my errors lies in the if statement.我相信我的错误在于 if 语句。 However, cant seem to figure it out.但是,似乎无法弄清楚。 I would be glad if somebody could help.如果有人能提供帮助,我会很高兴。

function word(s) {
  let str = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "zero"];
  let int = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];

  for (let j = 0; j < int.length; j++) {
    for (let i = 0; i < str.length; i++) {
      if (s === str[i]) {
        return int[j]
      }
    }
  }
}

Essentially what you're looking to do is get the index of the input s in your str array, and return the item at the same index in your int array.本质上,您要做的是获取str数组中输入s的索引,并返回int数组中相同索引处的项目。 You could accomplish this with just the one loop:您只需一个循环即可完成此操作:

function word(s) {
    let str = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "zero"];
    let int = [1,2,3,4,5,6,7,8,9,0];
  
    for (let j = 0; j < int.length; j++){
        if (s === str[j]){
         return int[j]
        }
    }
}

Of course, this is reliant upon the order of values matching up in your str and int arrays.当然,这取决于您的strint数组中匹配的值的顺序。

You need only a single loop to find the index of the given word.您只需要一个循环即可找到给定单词的索引。 If found return the value form the other array by using the actual index.如果找到,则使用实际索引从另一个数组返回值。

for (let i = 0; i < str.length; i++){
    if (s === str[i]) return int[i];
}

Actually, You dont need loop also.实际上,您也不需要循环。 You can rearrange the strings and return the index based on the arrangement of the word in array.您可以重新排列字符串并根据数组中单词的排列返回索引。

 const str = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]; function word(s) { return str.indexOf(s); } console.log(word("five")) \/\/ In case you dont want to change order function word1(s) { const str = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "zero"]; const index = str.indexOf(s); return index < 9 ? index+1 : 0 } console.log(word1("five")) console.log(word1("zero")) \/\/ Other way get index ussing findIndex function word2(s) { return str.findIndex(item => item === s); } console.log(word2("five")) \/\/ Other using single loop function word3(s) { for (let i in str) { if (str[i] === s) return i; } \/\/ Incase not found return -1; } console.log(word3("five"))<\/code><\/pre>

"

Another option is to make use of the Map object , which allows the creation of a list of key-value pairs.另一种选择是使用Map 对象,它允许创建键值对列表。 Then, if the key is known, the value can immediately be gotten.然后,如果知道密钥,则可以立即获取该值。

Under the hood this usually done via a hashing algorithm on the key, in which case the lookup for the key does not involve looping through all keys, but instead generates the hash from the key, a hash which is then used to directly find the value in the list.在幕后,这通常通过密钥上的哈希算法完成,在这种情况下,查找密钥不涉及遍历所有密钥,而是从密钥生成哈希,然后使用哈希直接查找值在列表中。 (It's a bit more complicated than that, but you can find out more by searching on array hashing techniques.) (它比这更复杂一些,但您可以通过搜索数组散列技术找到更多信息。)

So, the first step is to initialize the Map object by mapping the written version of the number as the key to the actual value of the number.所以,第一步是初始化 Map 对象,将写好的数字作为键映射到数字的实际值。

Then, once this mapping is created, for every instance where the lookup is required, it simply involves getting the value from the map.然后,一旦创建此映射,对于需要查找的每个实例,它只涉及从映射中获取值。

 function createMap( keyArray, valueArray ) { let map = new Map(); for ( let i = 0; i < keyArray.length; i++ ) { map.set( keyArray[ i ], valueArray[ i ] ); } return map; } let myMap = createMap( ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "zero"], [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] ) console.log( myMap.get( "four" ) ); console.log( myMap.get( "two" ) );

This then has the distinct advantage of directly returning the value corresponding to the key without having to search the list of keys every time...然后,这具有直接返回与键对应的值的明显优势,而不必每次都搜索键列表......

Working Demo:工作演示:

 function getStringNumber(word) { let str = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "zero"]; let int = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]; for (let i = 0; i < str.length; i++) { if (word === str[i]) return int[i]; } } console.log(getStringNumber('nine')?? 'No word found;');

暂无
暂无

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

相关问题 通过使用第二个数组(JavaScript)中的引用从第一个数组中的每个 object 中提取每个值来创建一个新数组 - Make a new array by extracting each value from each object in the 1st array using the references in the 2nd array (JavaScript) 如何通过使用Javascript或JQuery对第一个数组进行排序来对第二个数组进行排序? - How to sort 2nd array by sorting the 1st one using Javascript or JQuery? 第一个单词第一个字符第二个单词第二个字符直到数组结尾 - 1st word 1st character 2nd word 2nd character and on till the end of array 检查数组中的匹配键,如果找到,则取第二个数组条目,如果在 javascript 中不取第一个数组条目 - Check for matching key in array, if found take 2nd array entries if not take 1st array entries in javascript 在第一个数组元素中的第二个数组元素中查找字母 - Finding letters in 2nd array element in 1st array element 如果第二个数组匹配,则对第一个数组中的数字求和 - Summing numbers from 1st array if 2nd array match 比较第二个字符串字符与数组中的第一个字符串 - Compare the 2nd strings characters with the 1st string in an array 如何比较两个对象数组,如果第二个数组项值如此说明,则仅从第一个数组中删除项 - How to compare two arrays of objects and only remove items from 1st array if 2nd arrays item value says so 如何使用 GAS 将表单响应 object 转换为二维数组,其中第一行是键/标题,第二行是值/答案? - How to turn form responses object into a 2D array with the 1st row being the key/header and the 2nd the values/answers using GAS? 如何将数据从第二数组添加到第一数组以在Google Visualization API中显示图表 - how to add data from 2nd array to 1st array for showing chart in google Visualization api
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM