最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavaScript - Search for first character in an Array - Stack Overflow

programmeradmin4浏览0评论

I'm trying to find the first character in an Array in 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")

I do not have a lot of experience with JavaScript from before and I have been sitting with this problem for ages.

I'm trying to find the first character in an Array in 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")

I do not have a lot of experience with JavaScript from before and I have been sitting with this problem for ages.

Share Improve this question edited Jun 1, 2012 at 12:46 Kevin Bedell 13.4k10 gold badges80 silver badges115 bronze badges asked Jun 1, 2012 at 11:28 Jason StackhouseJason Stackhouse 1,8362 gold badges19 silver badges19 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 8

There's indexOf() method of an array/string which can provide you with a position of a letter. First letter has a position of 0(zero), so

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 jsFiddle for it. Before running open the console(Chrome: ctrl+shift+i, or console in FireBug) to see resulting arrays.

You can filter the array to contain only specific values, such as the ones starting with '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 aged browsers you might want to consider using underscore.js or Prototype

When using underscore you could simply write this:

var randomWordWithW = _.chain(words).filter(function(word) {
  return word[0] == 'w';
}).shuffle().first().value()
发布评论

评论列表(0)

  1. 暂无评论