5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

文字列はインデックスでアクセスできる

Last updated at Posted at 2017-07-27

文字列が入っているはずの変数に対しふと、console.log(foo[0])としてみたら配列に入れる前なのに1文字目が出力されてしまった。

javascript
var foo = "あいうえお";
console.log(foo[0]);	// => あ

意味がわからなくてデータの判別をしてみる。

javascript
console.log(typeof(foo));	// => String
console.log(Array.isArray(foo));	// => false

データはちゃんと文字列で配列ではない。どういうこと?

文字列はオブジェクト

MDN String
https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/String#Character_access

javascript
return 'ねこ'[1]; // "こ" が返される。

文字列をオブジェクトとして扱い、インデックスでアクセスできるとの事。

5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?