A. "string"
B. "function"
C. "object"
D. "null"
A. 輸入:typeof {"x":1} 輸出:"object"
B. 輸入:typeof 1 輸出:"number"
C. 輸入:typeof [{x:1}] 輸出:"array"
D. 輸入:typeof NaN 輸出:"number"
A. undefined
B. null
C. array
D. object
A. Boolean
B. undefined
C. Symbol
D. Array
A. 數據類型分為基本數據類型和引用數據類型
B. JavaScript一共有8種數據類型
C. Object是引用數據類型,且只存儲于堆(heap)中
D. BigInt是可以表示任意精度整數的基本數據類型,存儲于棧(stack)中
答案
DCADC
A. null instanceof Object
B. null === undefined
C. null == undefined
D. NaN == NaN
A. Symbol.for('a') === Symbol.for('a')
B. Symbol('a') === Symbol('a')
C. NaN === NaN
D. {} === {}
var a = 1;
var b = [];
var c = '';
var d = true;
A. (a || b) === true
B. (b && c) === true
C. (c && d) === true
D. (d || a) === true
A. T
B. F
A. console.log([] === []);
B. console.log(undefined == 0);
C. console.log(undefined == false);
D. console.log(false == '');
A. console.log("12" === 12)
B. console.log (NaN === NaN)
C. console.log (typeof(null) === typeof(window))
D. console.log ([1,2,3] === [1,2,3])
注意瀏覽器環境與node環境的差別,比如C選項
A. Number('a') == Number('a')
B. -1 == true
C. 3 + '2' === 5
D. ![] == ''
答案
CADADCD
A. Math.round(7.25)
B. Math.ceil(7.25)
C. round(7.25)
D. Math.rnd(7.25)
A. Math.floor(Math.random()*6)
B. Math.floor(Math.random()*10)
C. Math.floor(Math.random()*11)
D. Math.ceil(Math.random()*10)
A. Math.floor(Math.random()*6)
B. Math.floor(Math.random()*7)
C. Math. floor(Math.random()*8)
答案
A CD(注意D) C
A. T
B. F
A. match()
B. indexOf()
C. search()
D. concat()
答案
A BC
A. {name:"xiaoming",age,"student"}
B. {"name":"xiaoming","age":"student"}
C. {"xiaoming","student"}
D. ["xiaoming","student"]
const fn = function(){}
const res = JSON.stringify(fn)
const num = 123
const res = JSON.stringify(num)
const res = JSON.stringify(NaN)
const b = true
const res = JSON.stringify(b)
A. 'function'、'123'、'NaN'、'true'
B. undefined、'123'、undefined、'true'
C. undefined、'123'、'null'、'true'
D. undefined、'123'、'null'、undefined
答案
BC
A. push
B. concat
C. sort
D. shift
A. slice
B. splice
C. sort
D. unshift
A. push
B. pop
C. shift
D. unshift
A. push
B. pop
C. unshift
D. splice
A. concat
B. splice
C. slice
D. join
A. concat
B. shift
C. filter
D. map
A. push
B. slice
C. splice
D. sort
// (1)
const newNums = Array.from(new Set(nums))
// (2)
const newNums = nums.filter((n, i) => {
return nums.indexOf(n) === i
})
// (3)
const newNums = nums.forEach((n, i) => {
return nums.indexOf(n) === i
})
// (4)
const newNums = nums.reduce((acc, n, i) => {
return [].concat(acc, nums.indexOf(n) === i ? n : []
)
})
A. (1)、(2)、(3)、(4)
B. (1)、(3)、(4)
C. (1)、(2)、(4)
D. (1)、(4)
答案
BAABB
BBC
A. 123
B. 123a
C. d123
D. 123def
A. test
B. match
C. exec
D. compile
A. str.replace(`/\s*/g,""`)
B. str.replace(`/^\s|\s$/g,""`)
C. str.replace(`/^\s*/, ""`)
D. str.replace(`/(\s*$)/g, ""`)
答案
CBA
A. encodeURI
B. parseFloat
C. round
D. eval
A. 遵循嚴格模式:"use strict"
B. 將js腳本放在頁面頂部,加快渲染頁面
C. 將js腳本成組打包,減少請求,盡量減少使用閉包
D. 使用非阻塞方式下載js腳本,最小化重繪(repaint)和回流(reflow)
A. parseFloat方法:該方法將一個字符串轉換成對應的小數
B. isNaN方法:該方法用于檢測參數是否為數值型,如果是,返回true,否則,返回false。
C. escape方法: 該方法返回對一個字符串編碼后的結果字符串
D. eval方法:該方法將某個參數字符串作為一個JavaScript執行題
A. chrome
B. Safari
C. 搜狗瀏覽器
D. Firefox
// A
var formatDate=getDate()
// B
var formatDate = new Date()
// C
var formatDate = function (date) {
var y = date.getFullYear();
var m = date.getMonth() + 1;
var d = date.getDate();
return y + '-' + m + '-' + d;
};
// D
var formatDate = function (date) {
var y = date.getFullYear();
var m = date.getMonth() + 1;
m = m < 10 ? '0' + m : m;
var d = date.getDate();
d = d < 10 ? ('0' + d) : d;
return y + '-' + m + '-' + d;
};
A. 需要對元素進行復雜的操作時,可以先隱藏(display:"none"),操作完成后再顯示
B. 需要創建多個DOM節點時,使用DocumentFragment創建完后一次性的加入document
C. 盡量避免用table布局(table元素一旦觸發回流就會導致table里所有的其它元素回流)
D. 盡量不要使用 css 屬性簡寫,如:用border-width, border-style, border-color代替border
答案
CBBDDD
A. eval
B. apply
C. bind
D. call
A. 在使用new實例化對象時, this指向這個實例對象
B. 將對象的方法賦值給變量A。執行A()時 該方法中的this指向這個對象。
C. 在函數定義時,this指向全局變量
D. 在瀏覽器下的全局范圍內,this指向全局對象
A. call與apply都屬于Function.prototype的一個方法,所以每個function實例都有call、apply屬性
B. 兩者傳遞的參數不同,call函數第一個參數都是要傳入給當前對象的對象,apply不是
C. apply傳入的是一個參數數組,也就是將多個參數組合成為一個數組傳入
D. call傳入的則是直接的參數列表。call 方法可將一個函數的對象上下文從初始的上下文改變為由 thisObj 指定的新對象。
答案
AAB
// (1)
function getName() {
name = 'javascript'
}
getName()
// (2)
const elements = {
button: document.getElementById('button')
};
function removeButton() {
document.body.removeChild(elements.button);
}
removeButton()
// (3)
let timer = setInterval(() => {
const node = document.querySelector('#node')
if(node) {
clearInterval(timer)
}
}, 1000);
A. (1)、(2)、(3)
B. (2)、(3)
C. (1)、(3)
D. (1)、(2)
A. 沒有清理的DOM元素引用
B. 被遺忘的定時器
C. 事件偵聽沒有移除
D. 局部變量不用時,沒有設為null
A. 增加一定的內存消耗
B. 使用不當可能會導致內存泄漏
C. 可以使用閉包模擬私有方法
D. 閉包會改動對象的原型鏈
答案
DDD
A. 原型鏈繼承
B. 構造函數繼承
C. 組合繼承
D. 關聯繼承
A. T
B. F
A. 通過原型鏈繼承的屬性和對象自己定義的屬性等效
B. 通過原型鏈可以模擬對象的私有屬性
C. 在對象上訪問不存在的屬性時,會依次遍歷整條原型鏈
D. 所有 JavaScript 中的對象都是位于原型鏈頂端的 `Object` 的實例
答案
DBC
A. jsonp
B. cookie
C. localStorage
D. sessionStorage
答案
A
A. event.preventDefault()
B. event.prevent()
C. event.drag()
D. event.drop()
A. mouseover
B. click
C. mouseleave
D. mousemove
A. stopDeafault()
B. stopPropagation()
C. preventDefault()
D. preventDefaultEven()
目標 -> 捕獲 -> 冒泡
冒泡 -> 目標 -> 捕獲
目標 -> 冒泡 -> 捕獲
捕獲 -> 目標 -> 冒泡
A. onchange:用戶改變域的內容
B. onkeypress:某個鍵盤的鍵被按下或按住
C. onmousedown:某個鼠標按鍵被按下
D. onblur:元素獲得焦點
答案
ACCDD
A. parentObj.firstChild
B. parentObj.children
C. neborNode.previousSibling
D. neborNode.siblings
A. appendChild(parentNode,newNode);
B. append(parentNode,newNode);
C. parentNode.append(newNode);
D. parentNode.appendChild(newNode);
A. Array
B. Object
C. String
D. Function
A. appendChild(parentNode,newNode);
B. append(parentNode,newNode);
C. parentNode.append(newNode);
D. parentNode.appendChild(newNode);
答案
DDBD
outline
visiblity
font-size
background-color
答案
C
A. 每隔60秒調用一次updateClock()
B. 每隔60毫秒調用一次updateClock()
C. 每隔60分鐘調用一次updateClock()
D. 每分鐘調用60次updateClock()
A. Geolocation.watchPosition()
B. Geolocation.getCurrentPosition()
C. Geolocation.getPosition()
D. Geolocation.Position()
A. 等待1000秒后,再彈出一個對話框
B. 等待1秒鐘后彈出一個對話框
C. 每隔一秒鐘彈出一個對話框
D. 語句報錯,語法有問題
答案
BBC
A. 箭頭函數沒有原型屬性
B. 箭頭函數不綁定this,會捕獲其所在的上下文的this值,作為自己的this值
C. 箭頭函數可以作為構造函數,使用new
D. 箭頭函數不綁定arguments,取而代之用rest參數解決
A. 函數體內this的指向是定義時所在的對象,而不是使用時所在的對象
B. 箭頭函數內不能使用arguments對象
C. 箭頭函數不能使用yield命令
D. 可以使用new創建一個箭頭函數的實例
答案
CD
Promise.all([]).then((res) => {
console.log('all');
});
Promise.race([]).then((res) => {
console.log('race');
});
A. all 和 race 都會被輸出
B. all 和 race 都不會被輸出
C. all 會被輸出,而 race 不會被輸出
D. all 不會被輸出,race 會被輸出
A. Promise
B. Generator
C. async
D. Proxy
A. Pending
B. Pause
C. Fulfilled
D. Rejected
答案
CDB
let [a,b, c,d, e] = "hello";
A. e = "hello";
B. 其它都為undefined
C. 當中 a = "h", b = "e";
D. 語法報錯
答案
C
A. push
B. concat
C. splice
D. map
A. const a = 0xa1
B. const a = 076
C. const a = 0b21
D. const a = 7e2
(1)function
(2) object
(3) null
(4) array
(5) NaN
(6) bigint
(7) regexp
(8) undefined
A. (1)、(2)、(3)、(4)、(5)、(6)、(7)、(8)
B. (1)、(2)、(3)、(8)
C. (1)、(2)、(8)
D. (1)、(2)、(6)、(8)
A. typeof 'string'
B. String('string').toString()
C. 'string'.split('').sort().join('')
D. (function(string){return string})('string')
E. JSON.parse('{"string":"string"}').string
A. parseInt(46.8) `==` parseFloat(46.8)
B. NaN `!==` NaN
C. isNaN('abc') `==` NaN
D. typeof NaN `===` 'number'
A. Array.from(A)
B. [].slice.apply(A)
C. [...A]
D. [].map.call(A, o => o)
A. null == undefined
B. null === undefined
C. null === null
D. NaN == null
E. NaN === NaN
F. Infinity + 1 !== Infinity
答案
AC ABD D ABDE BD ABCD AC
function Person() { } var person = new Person();
A. 每一個原型都有一個constructor屬性指向關聯的構造函數。
B. 每一個對象都有一個prototype屬性。
C. Object.getPrototypeOf(person) === Person.prototype
D. person.constructor === Person
A. process.nextTick
B. promise
C. setTimeout
D. setInterval
答案
ACD AB
A. let聲明的變量值和類型都可以改變
B. const聲明的常量不可以改變
C. 兩者都不存在變量提升,同時存在暫時性死區,只能在聲明的位置后面使用
D. const可以先聲明再初始化,可以后賦值
A. Promise.all在所有給定的promise都fulfilled后才返回結果
B. Promise.race在給定的promise中,某個fulfilled后才返回結果
C. promise.then的回調函數中,可以返回一個新的promise
D. 對于一個向后臺獲取數據已經產生結果的promise:p1,再次調用p1.then,不會去重新發起請求獲取數據
答案
ABC CD
document.body.style.['background-color'] = '#fff'
document.body.style.setProperty('background-color', '#fff')
document.body.style = 'background-color': #fff'
document.body.style.fontSize = '14px'
A. event.cancelBubble = true;
B. event.stopPropagation();
C. event.preventDefault();
D. return false;
答案
BCD ABD
var x = typeof x
var res = typeof typeof x;
console.log(x, res)
var arr = [];
console.log(typeof arr, Object.prototype.toString.call(arr));
// case 1
function showCase(value) {
switch(value) {
case 'A':
console.log('Case A');
break;
case 'B':
console.log('Case B');
break;
case undefined:
console.log('Case undefined');
break;
default:
console.log('Case default');
}
}
showCase(new String('A'));
// case 2
function showCase(value) {
switch(value) {
case 'A':
console.log('Case A');
break;
case 'B':
console.log('Case B');
break;
case undefined:
console.log('Case undefined');
break;
default:
console.log('Case default');
}
}
showCase(String('A'));
<html>
<body>
<p id="demo"></p>
<script type="text/javascript">
var x = 10;
var y = "10";
document.getElementById("demo").innerHTML = Boolean(x == y);
</script>
</body>
</html>
function funcA(x){
var temp = 4;
function funcB(y){
document.write( ++x + y + (temp--));
}
funcB(5);
}
funcA(6)
var varArr = function(i,j,str) {
return j == 0 ? str : varArr(i,--j,(str+= " " + i[j]));
}
var arr = new Array('apple','orange','peach','lime');
var str = varArr(arr,arr.length,"");
alert(str);
function greetingMaker(greeting) {
function addName(name) {
greeting = greeting.split(' ').reverse().join("-");
return greeting + " " + name;
}
return addName;
}
var daytimeGreeting = greetingMaker("Good Day to you");
alert(daytimeGreeting(name));
String.prototype.GetNum = function() {
var regEx = /[^\d]/g;
return this.replace(regEx, '');
};
var str = "a1b2c3";
str = str.GetNum();
alert(str);
function sum(a, b) {
return a + b;
}
sum(1, "2");
var str = "我非常喜歡編程";
str.length = 3;
console.log(str);
let number = 0;
console.log(number++);
console.log(++number);
console.log(number);
function nums(a, b) {
if (a > b)
console.log('a is bigger')
else
console.log('b is bigger')
return a + b
}
console.log(nums(4, 2))
console.log(nums(1, 2))
function side(arr) {
arr[0] = arr[2];
}
function func1(a, b, c = 3) {
c = 10;
side(arguments);
console.log(a + b + c);
}
function func2(a, b, c) {
c = 10;
side(arguments);
console.log(a + b + c);
}
func1(1, 1, 1);
func2(1, 1, 1);
var a = 3;
var b = new Number(3);
var c = 3;
console.log(a == b);
console.log(a === b);
console.log(b === c);
var a = [];
a.push(1, 2);
a.shift(3, 4);
a.concat([5, 6]);
a.splice(0, 1, 2);
var a = {}, b = '123', c = 123;
a[b] = 'b';
a[c] = 'c';
console.log(a[b]);
// example 2
var a = {}, b = Symbol('123'), c = Symbol('123');
a[b] = 'b';
a[c] = 'c';
console.log(a[b]);
// example 3
var a = {}, b = {key:'123'}, c = {key:'456'};
a[b] = 'b';
a[c] = 'c';
console.log(a[b]);
null == undefined
0.1 + 0.2 == 0.3
typeof NaN
typeof Function
typeof Object
typeof {}
'a' + 1
'a' - 1
Function instanceof Object
Object instanceof Function
var array = []
for(var i = 0; i < 3; i++) {
array.push(() => i)
}
var newArray = array.map(el => el())
console.log(newArray)
function a(m, n) {
var b = function (l) {
return l <= m ? l * b(l + 1) : 1;
}
return b(m - n + 1);
}
console.log(a(4, 2));
console.log(typeof undefined == typeof NULL);
console.log(typeof function () {} == typeof class {});
var a = 10
var b = {
age: 11
}
function fn(x,y) {
--y.age;
return --x;
}
fn(a,b)
var number = 4;
var numberFactorial = (function (number){
return (number === 0)? 1: number* factorial(number-1)
})(number)
console.log(numberFactorial)
var array = []
for(var i = 0; i < 3; i++) {
array.push(() => i)
}
var newArray = array.map(el => el())
console.log(newArray)
function addToList(item, list) {
return list.push(item)
}
const result = addToList("nowcoder", ["hello"])
console.log(result)
const first = () => { console.log('first'); return false; }
const second = () => { console.log('second'); return true; }
console.log( first() && second() );
console.log( second() || first() );
var s='12ab3cd', arr=s.split(/\d/);
console.log(arr[3],arr[4])
function getAge(...args) {
console.log(typeof args);
}
getAge(21);
var arr=[1,2,3];
arr.push(arr.shift())
console.log(arr[1],arr[2])
題目解析:this指向題目解析及擴展[3]
關于this還可以看看:可能是最好的 this 解析了...
var x = 1;
var obj = {
x: 3,
fun:function () {
var x = 5;
return this.x;
}
};
var fun = obj.fun;
console.log( obj.fun(), fun() );
var a = 5;
function test() {
a = 0;
alert(a);
alert(this.a);
var a;
alert(a);
}
new test();
function fun () {
return () => {
return () => {
return () => {
console.log(this.name)
}
}
}
}
var f = fun.call({name: 'foo'})
var t1 = f.call({name: 'bar'})()()
var t2 = f().call({name: 'baz'})()
var t3 = f()().call({name: 'qux'})
let obj1 = {
a: 1,
foo: () => {
console.log(this.a)
}
}
// log1
obj1.foo()
const obj2 = obj1.foo
// log2
obj2()
const Person = (name="wang",age=10) => {
this.name = name;
this.age = age;
return this.name +' is '+ this.age + 'years old'
}
let result = new Person('zhang',11)
console.log(result)
var person = {
age: 18,
getAge: function() {
return this.age;
}
};
var getAge = person.getAge
getAge()
var name = 'global';
var obj = {
name: 'local',
foo: function(){
this.name = 'foo';
}.bind(window)
};
var bar = new obj.foo();
setTimeout(function() {
console.log(window.name);
}, 0);
console.log(bar.name);
var bar3 = bar2 = bar;
bar2.name = 'foo2';
console.log(bar3.name);
var obj = {
name:"zhangsan",
sayName:function(){
console.info(this.name);
}
}
var wfunc = obj.sayName;
obj.sayName();
wfunc();
var name = "lisi";
obj.sayName();
wfunc();
var name='test'
var a = {
name: 'ass',
getName: function() {
return this.name;
}
}
var b = a.getName;
b();
const promiseA = Promise.resolve('a')
promiseA. then((res) => {
console.log(res)
}).then((res) => {
console.log(res)
})
const promiseB = Promise.resolve('b')
promiseB. then((res) => {
console.log(res)
})
promiseB. then((res) => {
console.log(res)
})
setTimeout(() => {
console.log(1)
}, 0)
const P = new Promise((resolve, reject) => {
console.log(2)
setTimeout(() => {
resolve()
console.log(3)
}, 0)
})
P.then(() => {
console.log(4)
})
console.log(5)
setTimeout(function(){
console.log(1);
}, 0)
new Promise(function(resolve){
console.log(2);
resolve();
console.log(3);
}).then(function(){
console.log(4);
})
console.log(5);
(async () => {
console.log(1);
setTimeout(() => {
console.log(2);
}, 0);
await new Promise((resolve, reject) => {
console.log(3);
}).then(() => {
console.log(4);
});
console.log(5);
})();
new Promise((resolve) => {
console.log('1')
resolve()
console.log('2')
}).then(() => {
console.log('3')
})
setTimeout(() => {
console.log('4')
})
console.log('5')
var p1 = new Promise(function(resolve, reject){
resolve("2")
})
setTimeout(function(){
console.log("1")
},10)
p1.then(function(value){
console.log(value)
})
setTimeout(function(){
console.log("3")
},0)
setTimeout(function() {
console.log('setTimeout');
}, 0);
Promise.resolve().then(function() {
console.log('promise1');
}).then(function() {
console.log('promise2');
});
setTimeout(function() {
console.log(1)
},0)
new Promise(function executor(resolve){
console.log(2)
for (var i = 0; i<10000; i++) {
i - 9999 && resolve()
}
console.log(3)
}).then(function() {
console.log(4)
})
console.log(5)
<div class="outer">
<div class="inner"></div>
</div>
對應的js代碼如下:
var outer = document.querySelector('.outer');
var inner = document.querySelector('.inner');
function onClick() {
console.log('click');
setTimeout(function() {
console.log('timeout');
}, 0);
Promise.resolve().then(function() {
console.log('promise');
});
outer.setAttribute('data-random', Math.random());
}
inner.addEventListener('click', onClick);
outer.addEventListener('click', onClick);
當點擊class為inner的div塊時,控制臺依次輸出結果是什么?10. 下面程序的輸出結果是?
(async () => {
console.log(1);
setTimeout(() => {
console.log(2);
}, 0);
await new Promise((resolve, reject) => {
console.log(3);
}).then(() => {
console.log(4);
});
console.log(5);
})();
setTimeout(() => console.log('a'));
Promise.resolve().then(
() => console.log('b’);
).then(
() => Promise.resolve('c').then(
(data) => {
setTimeout(() => console.log('d'));
console.log('f');
return data;
}
)
).then(data => console.log(data));
console.log('one');
setTimeout(function() { console.log('two'); }, 0);
Promise.resolve()
.then(function() { console.log('three'); })
console.log('four');
setTimeout(function () {
console.log(C)
},0)
console.log('D')
new Promise(function(resolve){
console.log('E')
resolve()
console.log('F')
}).then(function() {
console.log('G')
})
console.log('H')
function log(msg, time) {
return new Promise((resolve) => {
setTimeout(() => {
console.log(msg);
resolve();
}, time);
});
}
則下面三段代碼輸出的結果是:
// 第一段代碼:
(async () => {
for (let i = 0; i < 5; i++) {
await log(i, 1000);
}
})();
// 第二段代碼:
(async () => {
[ 1, 2, 3, 4 ].forEach(async (i) => {
await log(i, 1000);
});
})();
// 第三段代碼:
(async () => {
for (const i of [ 1, 2, 3, 4 ]) {
await log(i, 1000);
}
})();
關于原型JS:看完這篇文章,徹底了解 “原型” & “this”
傳送門: 原型與原型鏈題目解析[4]
function Fn1(name) {
if(name){
this.name = name;
}
}
Fn1.prototype.name="jack"
let a = new Fn1();
console.log('a:', a.name);
function Fn2(name) {
this.name = name;
}
Fn2.prototype.name="jack"
let b = new Fn2();
console.log('b:', b.name);
var Foo = (function() {
var x = 0;
function Foo() {}
Foo.prototype.increment = function() {
++x;
console.log(x);
};
return Foo;
})();
var a = new Foo();
a.increment();
a.increment();
var b = new Foo();
a.increment();
var name = 'Jay'
function Person(name){
this.name = name;
console.log(this.name)
}
var a = Person('Tom')
console.log(name)
console.log(a)
var b = new Person('Michael')
console.log(b)
class A{}
class B extends A{}
const a = new A()
const b = new B()
a.__proto__
b.__proto__
B. __proto__
B. prototype.__proto__
b.__proto__.__proto__
function test() {
getName = function() {
Promise.resolve().then(() => console.log(0));
console.log(1);
};
return this;
}
test.getName = function() {
setTimeout(() => console.log(2), 0);
console.log(3);
};
test.prototype.getName = function() {
console.log(4);
};
var getName = function() {
console.log(5);
};
function getName() {
console.log(6);
}
test.getName();
getName();
test().getName();
getName();
new test.getName();
new test().getName();
new new test().getName();
var tmp = {};
var A = function() {};
A. prototype = tmp;
var a = new A();
A. prototype = {};
var b = Object.create(tmp);
b.constructor = A. constructor;
console.log(a instanceof A);
console.log(b instanceof A);
function Foo(){}
Foo.prototype.z = 3;
var obj = new Foo();
console.info(obj.z)
obj.z = 10;
console.info(obj.z);
delete obj.z;
console.info(obj.z);
const Book = {
price: 32
}
const book = Object.create(Book);
book.type = 'Math';
delete book.price;
delete book.type;
console.log(book.price);
console.log(book.type);
function sayHello() {
console.log(name);
console.log(age);
var name = "Tom";
let age = 18;
}
sayHello();
for (var i = 0; i < 3; i++) {
setTimeout(_ => {
console.log(i)
})
}
for (let i = 0; i < 3; i++) {
setTimeout(_ => {
console.log(i)
})
}
console.log(a);
var a = 'a';
console.log(b);
let b = 'b';
var foo = "Hello";
(function(){
var bar = " World";
alert(foo + bar);
})();
alert(foo + bar);
var a = 10;
(function () {
console.log(a)
a = 5
console.log(window.a)
var a = 20;
console.log(a)
})()
const a = 10
function runFunction() {
const a = 20
console.log('inside', a)
}
runFunction()
console.log('outside', a)
"use strict"
var name = 'Jay'
var person = {
name: 'Wang',
pro: {
name: 'Michael',
getName: function () {
return this.name
}
}
}
console.log(person.pro.getName)
var people = person.pro.getName
console.log(people())
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
<script>
var elements = document.getElementsByTagName("li");
for (var i=0;i<elements.length;i++){
elements[i].onclick =function( ){
alert(i);
};
}
compute(10,100);
var compute = function(A,B) {
console.info(A * B) ;
};
function compute(A,B){
console.info(A + B);
}
function compute(A,B){
console.info((A + B)*2);
}
compute(2,10);
meili()
function meili() {
console.log("meili")
}
mogu()
var mogu = function() {
console.log("mogu")
}
// 片段1
check('first');
function check(ars){
console.log(ars);
}
// 片段2
check('second');
var check= function(ars){
console.log(ars);
}
const student = {name: 'ZhangSan'}
Object.defineProperty(student, 'age', {value: 22})
console.log(student)
console.log(Object.keys(student))
function * cb(x, y) {
for(let i = Math.ceil(x); i <= y; i++) {
yield i;
}
}
var a = cb(6, 9);
console.log(a.next());
console.log(a.next());
function fn(...args) {
console.log(typeof args);
}
fn(21);
Promise.reject(0)
.catch(e => e)
.catch(e => console.log(e))
class Person {
constructor (name) {
this.name = name;
}
greet () {
console.log(`Hi, my name is ${this.name}`);
}
greetDelay (time) {
setTimeout(() => {
console.log(`Hi, my name is ${this.name}`);
}, time);
}
}
function getPersonInfo (one, two, three) {
console.log(one)
console.log(two)
console.log(three)
}
const person = 'Lydia'
const age = 21
getPersonInfo `${person} is ${age} years old`
// module.js
export default () => "Hello world"
export const name = "nowcoder"
// index.js
import * as data from "./module"
console.log(data)
// a.js
let a = 1
let b = {}
setTimeout(() => {
a = 2
b.b = 2
}, 100)
module.exports = { a, b }
// b.js
const a = require('./a')
console.log(a.a)
console.log(a.b)
setTimeout(() => {
console.log(a.a)
console.log(a.b)
}, 500)
<div id="box1">
<div id="box2">
content
</div>
</div>
<script>
const $ = document.querySelector.bind(document);
const box1 = $('#box1');
const box2 = $('#box2');
box1.addEventListener('click', () =>{
console.log('box1 true');
}, true);
box1.addEventListener('click', () =>{
console.log('box1 false');
}, false);
box2.addEventListener('click', () =>{
console.log('box2 true');
}, true);
box2.addEventListener('click', () =>{
console.log('box2 false');
}, false);
</script>
$(function () {
function fn1( value ) {
alert( value );
}
function fn2( value ) {
fn1("A");
return false;
}
var callbacks = $.Callbacks();
callbacks.add( fn1 );
callbacks.fire( "B" );
callbacks.add( fn2 );
callbacks.fire( "C" );
})
<html>
<head>
<script type="text/javascript" src="/jquery/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$("<b>Hello World!</b>").______("p");
});
});
</script>
</head>
<body>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>在每個p元素的結尾添加內容</button>
</body>
</html>
<div id="box1">
<div id="box2">
content
</div>
</div>
<script>
const $ = document.querySelector.bind(document);
const box1 = $('#box1');
const box2 = $('#box2');
box1.addEventListener('click', () => {
console.log('box1 true');
}, true);
box1.addEventListener('click', () => {
console.log('box1 false');
}, false);
box2.addEventListener('click', () => {
console.log('box2 true');
}, true);
box2.addEventListener('click', () => {
console.log('box2 false');
}, false);
</script>
牛客網的45道JS能力評測題個人覺得是非常好的45道js基礎檢測題,基本就是對自己的JavaScript基礎做一個比較全面的評估,包括if語句、循環體、基礎操作符、setInterval、setTimeout、流程控制、常用數組方法及es6相關(解構、Map、Set、...等)。之前我已經做過一遍了,我記得以前牛客網不支持es6的寫法,這兩天花了點時間把所有題目又做了一遍,發現支持es6了。這次每個題目我都盡力用了不同的方法實現,建議各位看官收藏,需要的時候方便查看。當然如果你有更好更新穎的實現方法,歡迎評論區留言交流。
我也把常用的數組方法和字符串方法貼在這里,可以自測掌握程度
第一題比較簡單,就直接上答案:
// 方法一
function indexOf(arr, item) {
if(Array.prototype.indexOf){// 判斷瀏覽器是否支持indexOf方法
return arr.indexOf(item);
}else{
for(var i=0;i<arr.length;i++){
if(arr[i]===item){
return i;
}
}
}
return -1;
}
// 方法二
function indexOf(arr, item) {
if(Array.prototype.indexOf){// 判斷瀏覽器是否支持indexOf方法
return arr.indexOf(item);
} else if (arr.indexOf(item) > 0) {
return arr.indexOf(item)
}else{
return -1
}
}
復制代碼
這里順便說一下Array.prototype.indexOf
indexOf()方法返回在數組中可以找到一個給定元素的第一個索引,如果不存在,則返回-1。
語法:
arr.indexOf(searchElement) //查找searchElement元素在數組中的第一個位置
arr.indexOf(searchElement[, fromIndex = 0]) //從fromIndex開始查找searchElement元素在數組中的第一個位置
復制代碼
還有另外一個查找字符串的方法String.prototype.indexOf()
str.indexOf(searchValue[, fromIndex])
復制代碼
具體可以看看MDN
方法一:普通的for循環拷貝+push
function append(arr, item) {
let resArr = []
for(let i = 0;i<arr.length;i++){
resArr.push(arr[i])
}
resArr.push(item)
return resArr
}
復制代碼
方法二:使用concat將傳入的數組或非數組值與原數組合并,組成一個新的數組并返回
function append(arr, item) {
return arr.concat(item);
}
復制代碼
方法三:使用slice淺拷貝+push
function append(arr, item) {
let newArr = arr.slice(0); // slice(start, end)淺拷貝數組
newArr.push(item);
return newArr;
}
復制代碼
方法四:...擴展運算符 如果不知道的,可以看看es6的相關知識
function append(arr, item) {
let resArr = [...arr,item]
return resArr
}
復制代碼
這里需要注意理解題目,是直接操作原數組,所以不能出現newArr
方法一:普通for循環+splice
function removeWithoutCopy(arr, item) {
for(let i=arr.length;i>=0;i--){
if(arr[i]==item){
arr.splice(i,1);
}
}
return arr;
}
復制代碼
方法二:方法一的另外一種寫法
在這里要注意在刪除掉一個元素時,要 i–,即刪除這個元素后,其他元素位置往前移。
function removeWithoutCopy(arr, item) {
for(let i = 0; i< arr.length; i++) {
if(arr[i]===item) {
arr.splice(i,1);
i--;
}
}
return arr;
}
復制代碼
把第3題稍微變一下,看下一題
方法一:filter過濾
function remove(arr, item) {
return arr.filter(res =>{
return res != item;
})
}
復制代碼
方法二:for循環+push
function remove(arr, item) {
let resArr = []
for(let i = 0;i<arr.length;i++){
if(arr[i]!== item){
resArr.push(arr[i])
}
}
return resArr
}
復制代碼
方法三:forEach+push(效率高于for循環)
function remove(arr, item) {
let resArr=[];
arr.forEach(v=>{
if(v!==item){
resArr.push(v);
}
})
return resArr;
}
復制代碼
方法四:for循環+splice
function remove(arr,item){
let resArr= arr.slice(0);
for(let i=0;i<resArr.length;i++){
if(resArr[i] == item){
resArr.splice(i,1);
i--;
}
}
return resArr;
}
復制代碼
方法一:普通for循環
function sum(arr) {
let res = 0
for(let i=0;i<=arr.length;i++){
res +=arr[i]
}
return res
}
復制代碼
方法二:forEach循環
function sum(arr) {
let res = 0
arr.forEach((value,index,array)=>{
array[index] == value; //結果為true
res+=value;
});
return res;
};
復制代碼
方法三:reduce
reduce() 方法接收一個函數作為累加器,數組中的每個值(從左到右)開始縮減,最終計算為一個值,具體可以看看es6相關知識。
function sum(arr) {
return arr.reduce((pre,cur)=>{
return pre+cur;
})
}
復制代碼
方法四:eval
eval() 函數可計算某個字符串,并執行其中的的 JavaScript 代碼。
function sum(arr) {
return eval(arr.join("+"));
}
復制代碼
關注后私信回復前端“” 可以觀看全部題目,還可以下載前端教程學習!
上就是畢業季了,很多同學都準備實習面試找工作了,今天來分享我在面試的畢業生的時候,會經常考察的16道JavaScript原理題,僅提供相應的核心原理和思路,具體細節大家可以收藏自己敲一遍研究理解。
一定要收藏自己練一遍!理解了才是自己的!
// 思路:將要改變this指向的方法掛到目標this上執行并返回
Function.prototype.mycall = function (context) {
if (typeof this !== 'function') {
throw new TypeError('not funciton')
}
context = context || window
context.fn = this
let arg = [...arguments].slice(1)
let result = context.fn(...arg)
delete context.fn
return result
}
// 思路:將要改變this指向的方法掛到目標this上執行并返回
Function.prototype.myapply = function (context) {
if (typeof this !== 'function') {
throw new TypeError('not funciton')
}
context = context || window
context.fn = this
let result
if (arguments[1]) {
result = context.fn(...arguments[1])
} else {
result = context.fn()
}
delete context.fn
return result
}
// 思路:類似call,但返回的是函數
Function.prototype.mybind = function (context) {
if (typeof this !== 'function') {
throw new TypeError('Error')
}
let _this = this
let arg = [...arguments].slice(1)
return function F() {
// 處理函數使用new的情況
if (this instanceof F) {
return new _this(...arg, ...arguments)
} else {
return _this.apply(context, arg.concat(...arguments))
}
}
}
function myNew (fun) {
return function () {
// 創建一個新對象且將其隱式原型指向構造函數原型
let obj = {
__proto__ : fun.prototype
}
// 執行構造函數
fun.call(obj, ...arguments)
// 返回該對象
return obj
}
}
function person(name, age) {
this.name = name
this.age = age
}
let obj = myNew(person)('chen', 18)
// {name: "chen", age: 18}
// 思路:將傳入的對象作為原型
function create(obj) {
function F() {}
F.prototype = obj
return new F()
}
// 思路:右邊變量的原型存在于左邊變量的原型鏈上
function instanceOf(left, right) {
let leftValue = left.__proto__
let rightValue = right.prototype
while (true) {
if (leftValue === null) {
return false
}
if (leftValue === rightValue) {
return true
}
leftValue = leftValue.__proto__
}
}
// 未添加異步處理等其他邊界情況
// ①自動執行函數,②三個狀態,③then
class Promise {
constructor (fn) {
// 三個狀態
this.state = 'pending'
this.value = undefined
this.reason = undefined
let resolve = value => {
if (this.state === 'pending') {
this.state = 'fulfilled'
this.value = value
}
}
let reject = value => {
if (this.state === 'pending') {
this.state = 'rejected'
this.reason = value
}
}
// 自動執行函數
try {
fn(resolve, reject)
} catch (e) {
reject(e)
}
}
// then
then(onFulfilled, onRejected) {
switch (this.state) {
case 'fulfilled':
onFulfilled()
break
case 'rejected':
onRejected()
break
default:
}
}
}
// 1. ...實現
let copy1 = {...{x:1}}
// 2. Object.assign實現
let copy2 = Object.assign({}, {x:1})
// 可避免setInterval因執行時間導致的間隔執行時間不一致
setTimeout (function () {
// do something
setTimeout (arguments.callee, 500)
}, 500)
// 借用構造函數繼承實例屬性
function Child () {
Parent.call(this)
}
// 寄生繼承原型屬性
(function () {
let Super = function () {}
Super.prototype = Parent.prototype
Child.prototype = new Super()
})()
// 1. JOSN.stringify()/JSON.parse()
let obj = {a: 1, b: {x: 3}}
JSON.parse(JSON.stringify(obj))
// 2. 遞歸拷貝
function deepClone(obj) {
let copy = obj instanceof Array ? [] : {}
for (let i in obj) {
if (obj.hasOwnProperty(i)) {
copy[i] = typeof obj[i] === 'object'?deepClone(obj[i]):obj[i]
}
}
return copy
}
// 組件通信,一個觸發與監聽的過程
class EventEmitter {
constructor () {
// 存儲事件
this.events = this.events || new Map()
}
// 監聽事件
addListener (type, fn) {
if (!this.events.get(type)) {
this.events.set(type, fn)
}
}
// 觸發事件
emit (type) {
let handle = this.events.get(type)
handle.apply(this, [...arguments].slice(1))
}
}
// 測試
let emitter = new EventEmitter()
// 監聽事件
emitter.addListener('ages', age => {
console.log(age)
})
// 觸發事件
emitter.emit('ages', 18) // 18
let obj = {}
let input = document.getElementById('input')
let span = document.getElementById('span')
// 數據劫持
Object.defineProperty(obj, 'text', {
configurable: true,
enumerable: true,
get() {
console.log('獲取數據了')
},
set(newVal) {
console.log('數據更新了')
input.value = newVal
span.innerHTML = newVal
}
})
// 輸入監聽
input.addEventListener('keyup', function(e) {
obj.text = e.target.value
})
// hash路由
class Route{
constructor(){
// 路由存儲對象
this.routes = {}
// 當前hash
this.currentHash = ''
// 綁定this,避免監聽時this指向改變
this.freshRoute = this.freshRoute.bind(this)
// 監聽
window.addEventListener('load', this.freshRoute, false)
window.addEventListener('hashchange', this.freshRoute, false)
}
// 存儲
storeRoute (path, cb) {
this.routes[path] = cb || function () {}
}
// 更新
freshRoute () {
this.currentHash = location.hash.slice(1) || '/'
this.routes[this.currentHash]()
}
}
// 思路:在規定時間內只觸發一次
function throttle (fn, delay) {
// 利用閉包保存時間
let prev = Date.now()
return function () {
let context = this
let arg = arguments
let now = Date.now()
if (now - prev >= delay) {
fn.apply(context, arg)
prev = Date.now()
}
}
}
function fn () {
console.log('節流')
}
addEventListener('scroll', throttle(fn, 1000))
*請認真填寫需求信息,我們會在24小時內與您取得聯系。