JavaScript - 搜索数组中的第一个字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10849402/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript - Search for first character in an Array
提问by Jason Stackhouse
I'm trying to find the first character in an Array in JavaScript.
我正在尝试在 JavaScript 中查找数组中的第一个字符。
I have this a random function (not the best, but I am going to improve it):
我有一个随机函数(不是最好的,但我会改进它):
function random() {
var Rand = Math.floor(Math.random()*myArray.length);
document.getElementById('tr').innerHTML = myArray[Rand];
}
And here's my Array list.
这是我的数组列表。
myArray = ["where", "to", "get", "under", "over", "why"];
If the user only wants arrays with W's, only words with a W in the first letter is shown. (Like "where" or "why")
如果用户只想要带有 W 的数组,则只显示第一个字母中带有 W 的单词。(比如“哪里”或“为什么”)
I do not have a lot of experience with JavaScript from before and I have been sitting with this problem for ages.
我以前对 JavaScript 没有太多经验,而且我已经解决这个问题多年了。
回答by lukas.pukenis
There's indexOf()
method of an array/string which can provide you with a position of a letter. First letterhas a position of 0(zero), so
有indexOf()
一个数组/字符串的方法可以为您提供一个字母的位置。第一个字母的位置为0(zero),所以
function filter(letter) {
var results = [];
var len = myArray.length;
for (var i = 0; i < len; i++) {
if (myArray[i].indexOf(letter) == 0) results.push(myArray[i]);
}
return results;
}
Here is a jsFiddlefor it. Before running open the console(Chrome: ctrl+shift+i, or console in FireBug) to see resulting arrays.
这是一个jsFiddle。在运行之前打开控制台(Chrome:ctrl+shift+i,或 FireBug 中的控制台)以查看结果数组。
回答by Tharabas
You can filter the array to contain only specific values, such as the ones starting with 'w'
您可以过滤数组以仅包含特定值,例如以“w”开头的值
var words = ["where", "to", "get", "under", "over", "why"];
var wordsWithW = words.filter(function(word) {
return word[0] == 'w';
});
var randomWordWithW = wordsWithW[Math.floor(Math.random() * wordsWithW.length];
... // operate on the filtered array afterwards
If you plan to support the agedbrowsers you might want to consider using underscore.jsor Prototype
如果您打算支持旧浏览器,您可能需要考虑使用underscore.js或Prototype
When using underscore you could simply write this:
使用下划线时,您可以简单地编写:
var randomWordWithW = _.chain(words).filter(function(word) {
return word[0] == 'w';
}).shuffle().first().value()