0
0

[JavaScript] Array(配列)のpush()メソッドのサンプルコード50個

Last updated at Posted at 2024-08-24

参考:
https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Array/push

おすすめ書籍
ググるのは時間の無駄です。基礎を書籍で抑えましょう。

独習JavaScript 新版

// 1. 単純に数字を追加
let numbers = [1, 2, 3];
numbers.push(4);
console.log(numbers); // [1, 2, 3, 4]

// 2. 文字列を追加
let fruits = ["apple", "banana"];
fruits.push("orange");
console.log(fruits); // ["apple", "banana", "orange"]

// 3. 配列に複数の数字を追加
let scores = [95, 80];
scores.push(100, 90);
console.log(scores); // [95, 80, 100, 90]

// 4. オブジェクトを追加
let users = [{name: "Alice"}, {name: "Bob"}];
users.push({name: "Charlie"});
console.log(users); // [{name: "Alice"}, {name: "Bob"}, {name: "Charlie"}]

// 5. 空の配列に要素を追加
let emptyArray = [];
emptyArray.push(1);
console.log(emptyArray); // [1]

// 6. 複数の文字列を追加
let colors = ["red"];
colors.push("green", "blue");
console.log(colors); // ["red", "green", "blue"]

// 7. 配列に別の配列を追加
let array1 = [1, 2];
let array2 = [3, 4];
array1.push(...array2);
console.log(array1); // [1, 2, 3, 4]

// 8. 条件付きで要素を追加
let conditionArray = [1, 2];
let value = 3;
if (value > 2) {
    conditionArray.push(value);
}
console.log(conditionArray); // [1, 2, 3]

// 9. 計算結果を追加
let calculatedArray = [10, 20];
let result = 10 * 2;
calculatedArray.push(result);
console.log(calculatedArray); // [10, 20, 20]

// 10. 未定義の値を追加
let misc = [null];
let undefinedValue;
misc.push(undefinedValue);
console.log(misc); // [null, undefined]

// 11. 多次元配列に要素を追加
let matrix = [[1, 2], [3, 4]];
matrix.push([5, 6]);
console.log(matrix); // [[1, 2], [3, 4], [5, 6]]

// 12. 配列の長さを増やす
let arrayLength = [1, 2, 3];
arrayLength.push(4);
console.log(arrayLength); // [1, 2, 3, 4]
console.log(arrayLength.length); // 4

// 13. 真偽値を追加
let booleanArray = [true, false];
booleanArray.push(true);
console.log(booleanArray); // [true, false, true]

// 14. 関数を配列に追加
let functionsArray = [];
functionsArray.push(function() { return "Hello"; });
console.log(functionsArray[0]()); // "Hello"

// 15. 配列にプロパティを持つオブジェクトを追加
let objectsArray = [{name: "Alice", age: 25}];
objectsArray.push({name: "Bob", age: 30});
console.log(objectsArray); // [{name: "Alice", age: 25}, {name: "Bob", age: 30}]

// 16. 配列に日付オブジェクトを追加
let dates = [new Date(2023, 0, 1)];
dates.push(new Date(2024, 0, 1));
console.log(dates); // [Date("2023-01-01"), Date("2024-01-01")]

// 17. 配列にnullを追加
let values = [1, 2, 3];
values.push(null);
console.log(values); // [1, 2, 3, null]

// 18. 変数の値を追加
let someValue = 42;
let valueArray = [];
valueArray.push(someValue);
console.log(valueArray); // [42]

// 19. 配列の最後の要素をpushで再追加
let repeatedArray = [1, 2, 3];
repeatedArray.push(repeatedArray[repeatedArray.length - 1]);
console.log(repeatedArray); // [1, 2, 3, 3]

// 20. 文字列と数字を一緒に追加
let mixedArray = [];
mixedArray.push("age", 30);
console.log(mixedArray); // ["age", 30]

// 21. ランダムな数値を追加
let randomArray = [];
randomArray.push(Math.random());
console.log(randomArray); // [0.XXXXXX](ランダムな値)

// 22. 文字列を連結して追加
let greetingArray = [];
let greeting = "Hello, " + "world!";
greetingArray.push(greeting);
console.log(greetingArray); // ["Hello, world!"]

// 23. インデックスを利用して要素を追加
let indexArray = [10, 20, 30];
let index = 1;
indexArray.push(indexArray[index] + 5);
console.log(indexArray); // [10, 20, 30, 25]

// 24. 配列の要素数に基づいて追加
let countArray = ["a", "b"];
countArray.push(countArray.length + 1);
console.log(countArray); // ["a", "b", 3]

// 25. ループを使って複数の要素を追加
let loopArray = [];
for (let i = 0; i < 3; i++) {
    loopArray.push(i * 2);
}
console.log(loopArray); // [0, 2, 4]

// 26. 計算した値を配列に追加
let calculationArray = [];
let x = 5;
let y = 3;
calculationArray.push(x + y);
console.log(calculationArray); // [8]

// 27. 配列に文字列として数値を追加
let stringNumbers = [];
let number = 100;
stringNumbers.push(number.toString());
console.log(stringNumbers); // ["100"]

// 28. プロパティ名を指定してオブジェクトを追加
let namedArray = [];
let object = {};
object["key"] = "value";
namedArray.push(object);
console.log(namedArray); // [{key: "value"}]

// 29. 既存の配列に要素を追加
let existingArray = [1, 2];
let anotherValue = 3;
existingArray.push(anotherValue);
console.log(existingArray); // [1, 2, 3]

// 30. 条件が真のときだけ要素を追加
let conditionalArray = [7, 8];
let condition = true;
if (condition) {
    conditionalArray.push(9);
}
console.log(conditionalArray); // [7, 8, 9]

// 31. 文字列配列に新しい単語を追加
let words = ["hello", "world"];
words.push("JavaScript");
console.log(words); // ["hello", "world", "JavaScript"]

// 32. 小数を配列に追加
let decimals = [];
decimals.push(0.1, 0.2, 0.3);
console.log(decimals); // [0.1, 0.2, 0.3]

// 33. 配列にオブジェクトを動的に作成して追加
let dynamicArray = [];
dynamicArray.push({id: 1, name: "Dynamic Object"});
console.log(dynamicArray); // [{id: 1, name: "Dynamic Object"}]

// 34. 配列に別の配列の要素を追加
let baseArray = [1, 2];
let extraArray = [3, 4];
baseArray.push(...extraArray);
console.log(baseArray); // [1, 2, 3, 4]

// 35. 配列に複数の文字列を連結して追加
let phrases = [];
phrases.push("Hello" + " " + "World");
console.log(phrases); // ["Hello World"]

// 36. 配列にインクリメントされた値を追加
let incrementArray = [0];
incrementArray.push(incrementArray[0] + 1);
console.log(incrementArray); // [0, 1]

// 37. 配列にランダムな文字列を追加
let randomStrings = [];
let possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
let randomChar = possible.charAt(Math.floor(Math.random() * possible.length));
randomStrings.push(randomChar);
console.log(randomStrings); // ["ランダムな文字"]

// 38. 配列に条件式の結果を追加
let conditionResultArray = [];
let a = 10, b = 20;
conditionResultArray.push(a > b ? a : b);
console.log(conditionResultArray); // [20]

// 39. 配列に関数の戻り値を追加
function getValue() {
    return 42;
}
let resultArray = [];
resultArray.push(getValue());
console.log(resultArray); // [42]

// 40. 配列に特定の位置の値を複製して追加
let duplicateArray = [5, 10, 15];
duplicateArray.push(duplicateArray[1]);
console.log(duplicateArray); // [5, 10, 15, 10]

// 41. 配列に複数の数値と文字列を混ぜて追加
let mixedValues = [];
mixedValues.push(100, "hello", true);
console.log(mixedValues); // [100, "hello", true]

// 42. 配列にランダムな整数を追加
let randomIntegers = [];
randomIntegers.push(Math.floor(Math.random() * 100));
console.log(randomIntegers); // [ランダムな整数]

// 43. 文字列配列にtoUpperCase()を使って追加
let lowerCaseArray = ["hello"];
lowerCaseArray.push(lowerCaseArray[0].toUpperCase());
console.log(lowerCaseArray); // ["hello", "HELLO"]

// 44. 配列に数値をシフト演算して追加
let shiftedValues = [];
let num = 8;
shiftedValues.push(num << 1);
console.log(shiftedValues); // [16]

// 45. 配列にテンプレートリテラルを使って追加
let templateArray = [];
let name = "Alice";
templateArray.push(`Hello, ${name}`);
console.log(templateArray); // ["Hello, Alice"]

// 46. 配列にオブジェクトのプロパティを動的に追加
let dynamicObjectArray = [];
let key = "dynamicKey";
let dynamicObject = {};
dynamicObject[key] = "value";
dynamicObjectArray.push(dynamicObject);
console.log(dynamicObjectArray); // [{dynamicKey: "value"}]

// 47. 配列にNaNを追加
let nanArray = [];
nanArray.push(NaN);
console.log(nanArray); // [NaN]

// 48. 配列に条件付きで要素を追加(論理積)
let logicalArray = [10];
logicalArray.push(logicalArray[0] && 20);
console.log(logicalArray); // [10, 20]

// 49. 配列にundefinedを条件付きで追加
let optionalArray = [];
let maybeValue;
optionalArray.push(maybeValue || "default");
console.log(optionalArray); // ["default"]

// 50. 配列に多重pushを使用して追加
Array.prototype.pushChain = function(...elements) {
    this.push(...elements);
    return this;
};
let multiplePushArray = [];
multiplePushArray.pushChain(1).pushChain(2).pushChain(3);
console.log(multiplePushArray); // [1, 2, 3]
0
0
2

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