HLJ 发布于
2022-01-22 18:22:10

81个JavaScript实例代码

下一篇文章:

js面试题

按值/引用传递

实例1

var a = {};

(function b ( a ) {
    a.a = 10;
    a = null;
})( a );

console.log(a);
//输出结果 {"a":10}

实例2

function Person(name) {
  if (name) this.options.name = name;
}

Person.prototype.options = {
  name: "Default name"
};

var foo = new Person("foo");
var bar = new Person("bar");

console.log(foo.options.name);
console.log(bar.options.name);
//输出结果 bar
//输出结果 bar

实例3

var foo = { n: 1 };
var bar = foo;
foo.x = foo = { n: 2 };
console.log(foo.x)
// 输出结果 undefined

实例4

var obj = {a: 1};
(function(obj) {
  obj = {a: 2};
})(obj);
console.log(obj.a);
// 输出结果 1

实例5

var User = function() {};

User.prototype.attributes = {
  isAdmin: false
};

var admin = new User("Sam");
var guest = new User("Bob");

admin.attributes.isAdmin = true;

console.log(admin.attributes.isAdmin);
console.log(guest.attributes.isAdmin);
// 输出结果 true
// 输出结果 true

实例6

function Car(color) {
  this.color = color;
}
var lada = new Car("Black");
Car.prototype.currentGear = 1;
console.log(++lada.currentGear);
console.log(Car.prototype.currentGear);
// 输出结果 2
// 输出结果 1

实例7

(function(a) {
  arguments[0] = 10;
  console.log(a)
  // 输出结果 10
  return a;
})(5);

实例8

var myObject = {
  price: 20.99,
  get_price: function() {
    return this.price;
  }
};
var customObject = Object.create(myObject);
customObject.price = 19.99;
delete customObject.price;
console.log(customObject.get_price());
// 输出结果 20.99

闭包

实例9

for (var i = 0; i < 5; i++) {
  setTimeout(function() {
    console.log(i);
  }, 1000);
}
// 输出结果 5
// 输出结果 5
// 输出结果 5
// 输出结果 5
// 输出结果 5

实例10

var func = [];
for (var i = 0; i < 5; i++) {
  func[i] = function() {
    console.log(i);
  };
}
func[3]();
// 输出结果 5

实例11

(function() {
  var a = b = 5;
})();
console.log(b);
// 输出结果 5
// 注意输出 a 时报错 Uncaught ReferenceError: a is not defined,闭包下a是局部变量

实例12

(function(x) {
  return (function(y) {
      console.log(x);
  })(2)
})(1);
// 输出结果 1

实例13

<button id="btn-0">Button 1!</button>
<button id="btn-1">Button 2!</button>
<button id="btn-2">Button 3!</button>
<script type="text/javascript">
    var prizes = ['A Unicorn!', 'A Hug!', 'Fresh Laundry!'];
    for (var btnNum = 0; btnNum < prizes.length; btnNum++) {
        // for each of our buttons, when the user clicks it...
        document.getElementById('btn-' + btnNum).onclick = function() {
            // tell her what she's won!
            console.log(prizes[btnNum]);
            console.log(btnNum)
            // 输出结果 undefined
            // 输出结果 3
        };
    }
</script>

实例14

const fn = () => {
 let a = 1;
 return () => {
   a++;
   return a;
 }
};
const fnRes = fn();

console.log(fnRes())
console.log(fnRes())
// 输出结果 2
// 输出结果 3

const fnRes2 = fn();

console.log(fnRes2())
console.log(fnRes2())
// 输出结果 2
// 输出结果 3

输出顺序

实例15

console.log(1);
setTimeout(function() {
  console.log(2);
}, 1000);
setTimeout(function() {
  console.log(3);
}, 0);
console.log(4);
// 输出顺序 1,4,3,2

实例16

function say(a) {
  console.log(a);
}
say(1);
setTimeout(say(2), 5000);
setTimeout(function() {
  say(3);
}, 1000);
setTimeout(say, 2000, 4);
// 输出结果 1,2,3,4

实例17

// 下一个代码打印 0,1,2,3,4,4,3,2,1,0 仅修改函数(不是循环)以获取输出为 4,3,2,1,0,0,1,2,3 ,4
// 修改前输出 0,1,2,3,4,4,3,2,1,0
var a = function(i) {
  console.log(i);
};
var b = function(i) {
  console.log(i);
};
for (var i = 0; i < 5; i++) {
  a(i);
}
for (var i = 4; i >= 0; i--) {
  b(i);
}
// 修改后输出 4,3,2,1,0,0,1,2,3 ,4
var a = function(i) {
  console.log(4-i);
};
var b = function(i) {
  console.log(4-i);
};
for (var i = 0; i < 5; i++) {
  a(i);
}
for (var i = 4; i >= 0; i--) {
  b(i);
}

实例18

(function() {
  console.log(1);
  setTimeout(() => console.log(2), 1000);
  setTimeout(() => console.log(3), 0);
  Promise.resolve(true).then(() => console.log(4));
  console.log(5);
})();
// 输出顺序 1,5,4,3,2

Hoisting and types

实例19

var a = 1;
function b() {
  a = 10;
  return;
  function a() {
  }
}
b();
console.log(a);
// 输出结果 1

实例20

var a = {};
var b = { key: 'b' };
var c = { key: 'c' };

a[b] = 123;
a[c] = 456;
console.log(a[b]);
// 输出结果 456

实例21

console.log("1" + 2);
console.log(2 + "1");
console.log(1 + 2 + 3 + 4 + "5");
// 输出结果 12, 21, 105

实例22

function test() {
  console.log(a);
  console.log(foo());

  var a = 1;

  function foo() {
    return 2;
  }
}
test();
// 输出结果 undefined, 2

实例23

(function() {
  console.log(inner);
  // 输出结果 :
  // inner() {
  //   console.log('inner');
  // }

  inner();
  function inner() {
    console.log('inner');
    // 输出结果 :inner
  }
})();

实例24

(function() {
  console.log(inner);
  inner();
  var inner = function() {
    console.log('inner');
  }
})();
// 输出结果 undefined, inner is not a function

实例25

(function() {
  f();
  f = function() {
    console.log(1);
  }
})();
function f() {
  console.log(2)
}
f();
// 输出结果 2, 1

实例26

(function() {
  var x = 1;

  function x() {};

  console.log(x);
})();
// 输出结果 1

实例27

var f = function g(){ return 23; };
console.log(typeof g())
// 输出结果 g is not defined

实例28

var y = 1, x = y = typeof x;
console.log(x);
// 输出结果 undefined

实例29

var x = [typeof x, typeof y][1];
console.log(typeof typeof x);
// 输出结果 string

实例30

(function(foo){
  console.log(typeof foo.bar)
  return typeof foo.bar;
})({ foo: { bar: 1 } });
// 输出结果 undefined

实例31

(function() {
    logMe();
    var logMe = function() {
        console.log('Jesus, George, it was a wonder I was even born.');
    };
    logMe();

    function logMe() {
        console.log('Great Scott!');
    }
    logMe();
})();
// 输出结果:
// Great Scott!
// index.html:14 Jesus, George, it was a wonder I was even born.
// index.html:14 Jesus, George, it was a wonder I was even born.

实例32

console.log(new String('Hello') === 'Hello')
// 输出结果 false

实例33

console.log("This is a string" instanceof String)
// 输出结果 false

实例34

var a = 1;
var b = function() {
 a = 10;
 return a;
 function a() {
   a = 5;
  }
};
console.log(b(), a);
// 输出结果 10, 1

实例35

let test = (function f(){
  function f(){ return 1; }
  return f();
  function f(){ return 2; }
})();
console.log(test)
// 输出结果2

实例36

function f(){ return f; }
console.log(new f() instanceof f)
// 输出结果 false

实例37

var text = 'outside';
function logIt(){
    console.log(text);
    var text = 'inside';
};
logIt();
// 输出结果 undefined

实例38

(function() {
 var a = 'initial';
  if(a) {
    function f() { console.log("1"); };
  } else {
    function f() { console.log("2"); };
  }
  f();
})();
// 输出结果 1

实例39

(function() {
 var a = 0;
  f();
  if( a ) {
    function f() { console.log("1"); };
  } else {
    function f() { console.log("2"); };
  }
})();
// 输出结果 f is not a function

实例40

falseStr = "false";
if(true){
  var falseStr;
  if(falseStr){
   console.log("false" == true);
   console.log("false" == false);
  }
}
// 输出结果 false, false

实例41

var a = (1,2,3);
console.log(a);
// 输出结果 3

实例42

(function() {
   var a = b = 5;
})();
console.log(b);
// 输出结果 5

实例43

var a = {
  currentValue: 0,
  valueOf() {
     return this.currentValue += 1
  }
}
var eq = (a == 1 && a == 2 && a == 3);
console.log(eq); // awesome =)
// 输出结果 true

实例44

foo();

var foo = function() {
  console.log(false);
}

foo();

function foo() {
  console.log(true);
}

foo();
// 输出结果 true, false, false

Inheritance and context

实例45

var person = {
  name: "Sam",
  hello: function() {
    console.log(this.name);
  }
};
var hello = person.hello;
hello(); // Make it to output "Sam"
// 输出空值

实例46

function A() {
  this.value = 1;
}
var B = function() {} ;
/* put your code here */
var b = new B;
console.log(b.value === undefined) // should be true
console.log(b instanceof A) // should be true
// 输出结果 true, false

实例47

Logger = function(logFn) {
  _logFn = logFn;
  this.log = function(message) {
    _logFn(new Date() + ": " + message);
  }
};
var logger = new Logger(console.log);
logger.log("Hi!");
logger.log("Wazzup?");
// 输出结果 
// Mon Feb 14 2022 17:21:55 GMT+0800 (中国标准时间): Hi!
// Mon Feb 14 2022 17:21:55 GMT+0800 (中国标准时间): Wazzup?

实例48

function User(name) { this.name = name; }
var u1 = User('Bob');
var u2 = new User('Sam');
var u3 = User.call({}, 'Mike'); // <-- N.B.
console.log(u1)
console.log(u2)
console.log(u3)
// 输出结果 undefined, {name: 'Sam'}, undefined

实例49

var foo = {
  bar: function() { return this.baz; },
  baz: 1
};
(function(){
  console.log(typeof arguments[0]())
  return typeof arguments[0]();
})(foo.bar);
// 输出结果 undefined

实例50

var foo = {
  bar: function(){ return this.baz; },
  baz: 1
}

console.log(typeof (f = foo.bar)())
// 输出结果 undefined

实例51

var x = 10;
var foo = {
  x: 20,
  bar: function () {
    var x = 30;
    return this.x;
  }
};
console.log(
  foo.bar(),
  (foo.bar)(),
  (foo.bar = foo.bar)(),
  (foo.bar, foo.bar)()
);
// 输出结果 20, 20, 10, 10

实例52

function f(x, y) {
  x = 10;
  console.log(
    arguments[0],
    arguments[1]
  );
}
f();
// 输出结果 undefined undefined

Quirks

实例53

a = [1,2,3,4]
a[1.5] = 1.5
console.log(a)
// 输出结果 [1, 2, 3, 4, 1.5: 1.5]

实例54

function foo(){console.log("hello")}
foo.call.call.call.apply(function bar(x) {console.log(x)}, [this,"world"])
// 输出结果 world

实例55

var a;
/* put your code here */
a !== a; // should be true

实例56

var scores = [98, 74,85, 77, 93,100,89];
var total = 0;
for (var score in scores) { 
  total += score;
} 
var mean = total / scores.length;
console.log(mean); //?
// 输出结果 17636.571428571428

实例57

console.log([2, 3, -1, -6, 0, -108, 42, 10].sort())
// 输出结果 [-1, -108, -6, 0, 10, 2, 3, 42]

实例58

var y = 1;
if (function f(){}) {
  y += typeof f;
}
console.log(y);
// 输出结果 1undefined

实例59

var foo = function bar(){ return 12; };
typeof bar();
// 输出结果 报 bar is not defined 错

实例60

console.log(['11','11','11','11'].map(parseInt))
// 输出结果 [11, NaN, 3, 4]

实例61

function aaa() {
    return
    {
        test: 1
    };
}
console.log(typeof aaa());
// 输出结果 undefined

实例62

function bar() {
    return foo;
    foo = 10;
    function foo() {}
    var foo = '11';
}
console.log(typeof bar());
// 输出结果 function

实例63

console.log("1" - - "1")
// 输出结果 2

实例64

var x = 3;
var foo = {
    x: 2,
    baz: {
        x: 1,
        bar: function() {
            return this.x;
        }
    }
}
var go = foo.baz.bar;

console.log(go());
console.log(foo.baz.bar());
// 输出结果 3, 1

实例65

let myArr = ['foo', 'bar', 'baz'];
myArr.length = 0;
myArr.push('bin');

console.log(myArr);
// 输出结果 ['bin']

实例66

var x = 0;
function foo() {
    x++;
    this.x = x;
    return foo;
}
var bar = new new foo;

console.log(bar.x);
// 输出结果 undefined

实例67

var bar = 1,
    foo = {};
foo: {
    bar: 2;
    baz: ++bar;
};

console.log(foo.baz + foo.bar + bar)
// 输出结果 NaN

实例68

var myArr = ['foo', 'bar', 'baz'];
myArr[2];

console.log('2' in myArr);
// 输出结果 true

实例69

function foo(a, b) {
    arguments[1] = 2;
    console.log(b);
}
foo(1);
// 输出结果 undefined

实例70

function foo(){}
delete foo.length;
console.log(typeof foo.length);
// 输出结果 number

实例71

var f = (function f(){ return "1"; }, function g(){ return 2; })();
console.log(typeof f)
// 输出结果 number

实例72

var a = 1,
    b = function a(x) {
        x && a(--x);
    };
console.log(a);
// 输出结果 1

实例73

function a() {
    console.log(this);
}
a.call(null);
// 输出结果 window 所有对象

实例74

var foo = bar ? bar : 0;
// 输出结果 报错  Uncaught ReferenceError: bar is not defined 

实例75

var a = (1,5 - 1) * 2
console.log(a)
// 输出结果 8

实例76

setTimeout(function() {
  setTimeout(function() {
    console.log('foo');
  }, 50);
}, 100);
setTimeout(function() {
  setTimeout(function() {
    console.log('baz');
  }, 100);
}, 50);
// 输出结果 baz, foo

实例77

console.log(5 > 3 > 2)
// 输出结果 false

实例78

var a;
if (a = (1+1==2)) {
    console.log(a);
} else {
    console.log('false');
}
// 输出结果 true

实例79

console.log(1 << 33)
console.log((1 << 31) << 2)
// 输出结果 2, 0

实例80

function b(b) {
  return this.b && b(b)
}
console.log(b(b.bind(b)))
// 输出结果 undefined

实例81

var g = 0;
g = 1 && g++;
console.log(g);
// 输出结果 0
当前文章内容为原创转载请注明出处:http://www.good1230.com/detail/2022-01-22/575.html
最后生成于 2023-06-27 21:38:07
下一篇文章:

js面试题

此内容有帮助 ?
0