2
1

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 3 years have passed since last update.

javascriptにおけるメソッド

Last updated at Posted at 2020-12-30

#splice
配列から要素を取り除いたり、置き換えたり、追加したりするメソッド。

配列.splice()と記述する。

4つまで引数を記述することができ、第一引数は必須で、指定した数字以降の要素を取り出す。
第二引数は、第一引数で指定した要素以降から指定分だけ取り出す。
第三引数以降は、第一引数で指定した位置以降に、その値を配列に追加する。
参考)https://techacademy.jp/magazine/37922

spliceの返り値は配列で返ってくる。なので数値で返り値が欲しい場合は、配列の一番目を取り出すという意味で[0]を付けてあげる。
参考)https://dotinstall.com/lessons/bingo_js/55004

#JavaScriptからhtmlに画像を埋め込む

html

<img id="main">

javascript

const images = [
    'img/pic00.png',
    'img/pic01.png',
    'img/pic02.png',
    'img/pic03.png',
    'img/pic04.png',
    'img/pic05.png',
    'img/pic06.png',
    'img/pic07.png',
  ];
let currentIndex = 0;

const mainImage = document.getElementById('main');
mainImage.src = images[currentIndex];

①htmlのidをまずは取得して、キャッシュする
②そのキャッシュした値に.srcを付随させて配列に入れておいた画像を選択する。

また、JavaScriptでsrc属性の値を取得・変更する方法は以下のサイト参照。
参考)http://sarchitect.net/10364

#forEach
配列に格納されたデータを一気に取り出す。

構文
配列.forEach(function(item,index)){
 // itemに関する処理
}
使用例
var fruits = [ "apple", "orange", "melon" ];
   fruits.forEach( function( item ) {
   console.log( item ); 
 });

実行結果
apple
orange
melon

また、forEach()で渡す引数を2つにすると(構文のindexのこと)、この配列の中で何番目であるかを2番目の引数であるindexで表現できるようになる。
参考)https://techacademy.jp/magazine/14635

#classlist
特定のクラスを追加したり、削除したりするプロパティ。

参考)https://qiita.com/tomokichi_ruby/items/2460c5902d19b81cace5
https://techacademy.jp/magazine/27026

2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?