iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 14
0
Modern Web

JavaScript 30實作心得筆記系列 第 14

Day14 JavaScript References VS Copying

Day14 JavaScript References VS Copying

第14天的實作是要解釋js的變數內容為數字,布林值,字串跟變數內容為陣列和物件的差異性。

本章節的重點在 Javascript中by value 與 by reference的差異。

在本篇的重點要認識Javascript的基本型別物件型別之間的差異。

在Javascript有六個基本型別( 字串, 數字, 布林值, null, undefined, symbol),除了六個基本型別之外,還有物件型別( 陣列(Array), 物件(Object))。

基本型別中( 字串, 數字, 布林值是不可變的,物件型別( 陣列(Array), 物件(Object))是可變的

在實作中提到當變數age為100,age2age,其結果都是100,但把age設為200後,其結果顯示出來age為200,age2為100。

let age = 100;
let age2 = age;
console.log(age, age2);
// age: 100 age2: 100
age = 200;
console.log(age, age2);
// age: 200 age2: 100

這顯示Javascript在變數建立時,age2變數的值是指向age,但建立age2變數,是指向新的位置。

let name = 'Wes';
let name2 = name;
console.log(name, name2);
// name: Wes name2: Wes
name = 'wesley';
console.log(name, name2);
// name: wesley name2: wesley

在字串的型別時,其結果也是與數字的結果相同。

const players = ['Wes', 'Sarah', 'Ryan', 'Poppy'];
const team = players;
console.log(players, team);

在使用陣列的時候會發現,當players指定給team後,修改team的內容,再去檢查發現playersteam的一起被修改。

const players = ['Wes', 'Sarah', 'Ryan', 'Poppy'];
const team = players;
console.log('players:', players, 'team:', team);
team[3] = 'Lux';
console.log('players:', players, 'team:', team);

下面提供幾個方法是讓可以改變從原本陣列衍生出的變數陣列,卻不會變動到原本的的陣列。

  • Array.slice()
    team2的方法是players使用Array.splice()的方式轉換過去,會發現此時修改team2的值不會變動到players
const team2 = players.slice();
console.log('players', players, 'team2', team2);
team2[3]='team2_test'
console.log('players', players, 'team2', team2);

  • Array.concat()
const team3 = [].concat(players);
console.log('players', players, 'team3', team3);
team3[3]='team3_test'
console.log('players', players, 'team3', team3);

const team4 = [...players];
console.log('players', players, 'team4', team4);
team4[3] = 'team4_test';
console.log('players', players, 'team4', team4);

  • Array.from()
const team5 = Array.from(players);
console.log('players', players, 'team5', team5);
team5[3] = 'team5_test';
console.log('players', players, 'team5', team5);

最後是object

const person = {
      name: 'Wes Bos',
      age: 80
    };
const captain = person;
console.log('person', person, 'captain', captain);
captain.number = 99;
console.log('person', person, 'captain', captain);

console.log('person', person);
const cap2 = Object.assign({}, person, { number: 99, age: 12 });
console.log('person', person, 'cap2', cap2);

在多階層的object時會發現只有第一層修改時,不會相互影響到,但在第二層發現會相互影響。

因此使用JSON.stringify()的方式先將其轉換為字串,在使用JSON.parse()的方式將其轉回物件。這樣就屬於一個新的物件。

Javascript到底是傳址還是傳值呢?不過最近有看過說Javascript是靠by sharing的方式來進行。參考資料

但目前還無法理解其緣由,因此只能提供參考資料。

Javascript

  1. JSON
    The JSON object contains methods for parsing JavaScript Object Notation (JSON) and converting values to JSON. It can't be called or constructed, and aside from its two method properties it has no interesting functionality of its own.

  2. JSON.stringify()
    JSON.stringify() 方法把會把一個JavaScript的數值或是物件轉換成JSON字串。

JSON.stringify({});                  // '{}'
JSON.stringify(true);                // 'true'
JSON.stringify('foo');               // '"foo"'
JSON.stringify([1, 'false', false]); // '[1,"false",false]'
JSON.stringify({ x: 5 });            // '{"x":5}'

JSON.stringify(new Date(2006, 0, 2, 15, 4, 5)) 
// '"2006-01-02T15:04:05.000Z"'

JSON.stringify({ x: 5, y: 6 });
// '{"x":5,"y":6}'
JSON.stringify([new Number(3), new String('false'), new Boolean(false)]);
// '[3,"false",false]'

JSON.stringify({ x: [10, undefined, function(){}, Symbol('')] }); 
// '{"x":[10,null,null,null]}' 
 
// Symbols:
JSON.stringify({ x: undefined, y: Object, z: Symbol('') });
// '{}'
JSON.stringify({ [Symbol('foo')]: 'foo' });
// '{}'
JSON.stringify({ [Symbol.for('foo')]: 'foo' }, [Symbol.for('foo')]);
// '{}'
JSON.stringify({ [Symbol.for('foo')]: 'foo' }, function(k, v) {
  if (typeof k === 'symbol') {
    return 'a symbol';
  }
});
JSON.stringify( Object.create(null, { x: { value: 'x', enumerable: false }, y: { value: 'y', enumerable: true } }) );
  1. JSON.parse()
    JSON.parse() 方法把會把一個JSON字串轉換成 JavaScript的數值或是物件。
JSON.parse('{}');              // {}
JSON.parse('true');            // true
JSON.parse('"foo"');           // "foo"
JSON.parse('[1, 5, "false"]'); // [1, 5, "false"]
JSON.parse('null');            // null
tags:JSON, Array, Object

上一篇
Day13 Slide In on Scroll
下一篇
Day15 LocalStorage and Event Delegation
系列文
JavaScript 30實作心得筆記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言