0
0

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 1 year has passed since last update.

JavaScript の関数の引数に {value1, value2} が指定される場合の挙動を調べてみた

Last updated at Posted at 2023-03-25

追記: 2023-03-26

該当の記法は、分割代入 (Destructuring) と呼ばれ、ES2015 に追加された言語仕様ということを教えてもらいました。

わからないので調べようにも、"javascript {} 代入" では満足な検索結果は得られなかったので、JavaScript を独習している人にとって優しくないよね。

何がわからないかというと

例えば、このページ Basic Features: Pages | Next.js に記載されているサンプルコードで、

export default function Blog({ posts }) {
  return (
    <ul>
      {posts.map((post) => (
        <li>{post.title}</li>
      ))}
    </ul>
  )
}

export async function getStaticProps() {
  // Call an external API endpoint to get posts
  const res = await fetch('https://.../posts')
  const posts = await res.json()

  // By returning { props: { posts } }, the Blog component
  // will receive `posts` as a prop at build time
  return {
    props: {
      posts,
    },
  }
}

export default function Blog({ posts }) {

に記述されている ({ posts }) がどういう挙動なのかわからなかった。

ということで、挙動を確認してみた

次のコードを JSFiddle で動作させてみた。

var test = 1;
var hoge = 'fuga';
var example = {
    name: {
        test,
        test1: test,
        hoge,
        fiz: 'buzz',
    },
};

console.log(example);
console.log('example.name.test has ' + example.name.test);
console.log('example.name.fiz has ' + example.name.fiz);
var {test1} = example.name
console.log('test1 has ' + test1);

func1 = function(obj) {
    console.log('func1 prints out ' + obj.hoge);
}

func2 = function({ hoge, test }) {
    console.log('func2 prints out ' + hoge);
}

func1(example.name);
func2(example.name);

cosole.log() の出力結果は下記の通り。

{
  name: {
    fiz: "buzz",
    hoge: "fuga",
    test: 1,
    test1: 1
  }
}
"example.name.test has 1"
"example.name.fiz has buzz"
"test1 has 1"
"func1 prints out fuga"
"func2 prints out fuga"

感想

export default function Blog({ posts }) {

の挙動はなんとはなく想像は出来た。

しかし、次のような記述をする場合、

var {test1} = example.name

他の言語だと、

test1 = {
  fiz: "buzz",
  hoge: "fuga",
  test: 1,
  test1: 1
}

というような挙動を想定してしまう。

スプレッド構文とはまた違うのだろうし、この記法の正式な名称は何だろうか?`

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?