LoginSignup
0
0

More than 1 year has passed since last update.

配列を文字列に変換する際の注意点

Last updated at Posted at 2022-03-29

環境

node.js v10.19.0
Ubuntu 20.4

動作確認

配列を定義します。

node.js
var ary = [];

空の配列が返されます。

node.js
console.log(ary);       // => []

存在しない要素を指定すると、undefinedが返されます。

node.js
console.log(ary[0]);        // => undefined

空の配列に値をセットします。

node.js
ary.push("米原");
ary.push("彦根");
console.log(ary);           // => [ '米原', '彦根' ]

配列かどうか判断する方法です。

node.js
console.log(Array.isArray(ary));        // => true

型で判断するやり方もあります。 ただし、object型ではあることは分かっても、arry型であるかまでの判断はおこなえません。

node.js
console.log(typeof(ary));           // => object

配列を文字列にするには、2通りのやり方があります。

node.js
console.log(ary.join());            // => 米原,彦根
console.log(ary.toString());        // => 米原,彦根

少し強引っぽい印象ではあるが、このようなやり方で配列⇒文字列に変換する方法もあります。

node.js
console.log(ary + "");              // => 米原,彦根

このように記述すると、配列が文字列に変換されてログ表示されることになります。つまり、[米原,彦根]と配列でログ出力されることを期待していたが、米原,彦根と文字列でログ出力されることになります。

node.js
console.log("aryの内容は? : " + ary);

確かに、配列型でなくなっていることが確認できます。

node.js
console.log(Array.isArray(ary + ""));       // false

String型になっています。

node.js
console.log(typeof(ary + ""));      // => string

配列型を表示させたい時は、このようなログ出力の仕方もできます。

node.js
console.log("aryの内容は? : %O",  ary);      // [米原,彦根]
0
0
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
0
0