Home  >  Article  >  Web Front-end  >  JS interview questions (must read for interviews)

JS interview questions (must read for interviews)

PHP中文网
PHP中文网Original
2017-06-22 14:16:433603browse

1.What data types are returned by typeof in javascript?

  alert(typeof [1, 2]); //object 
    alert(typeof 'leipeng'); //string 
    var i = true;  
    alert(typeof i); //boolean 
    alert(typeof 1); //number 
    var a;  
    alert(typeof a); //undefined
    function a(){};
    alert(typeof a) //function

2. Give examples of 3 forced type conversions and 2 implicit type conversions?
Forcing (parseInt(), parseFloat( ),Number())
Implicit (==,!!)

3. The difference between split() and join()
The former is cut into an array, the latter is Convert the array into a string

4. Array method pop() push() unshift() shift()
Push() Add pop() to the tail and delete to the tail
Unshift() Add shift to the head ()Header deletion

5. What is the difference between event binding and ordinary events?
Normal method of adding events:

var btn = document.getElementById("hello");
btn.onclick = function(){
alert(1);
}
btn.onclick = function(){
alert(2);
}

Executing the above code will only alert 2
Event binding method to add events:

var btn = document.getElementById("hello");
btn.addEventListener("click",function(){
alert(1);
},false);
btn.addEventListener("click",function(){
alert(2);
},false);

Execution of the above code will first alert 1 and then alert 2
The ordinary method of adding events does not support adding multiple events. The bottom event will Override the above, and multiple events can be added by event binding (addEventListener).
addEventListener is not compatible with lower versions of IE
Ordinary events cannot be canceled
addEventListener also supports event bubbling + event capture

6. The difference between IE and DOM event streams
1. Execution order Different,
2. Parameters are different
3. Whether to add on event or not
4.This points to the question

7.What are the compatibility writing methods between IE and standards

var ev = ev || window.event 
document.documentElement.clientWidth || document.body.clientWidth 
var target = ev.srcElement||ev.target

8. The difference between call and apply
call method:
Syntax: call(thisObj, Object1,Object2...)
Definition: Call a method of an object to another An object replaces the current object.
Description:
The call method can be used to call a method instead of another object. The call method changes the object context of a function from the initial context to the new object specified by thisObj.
If the thisObj parameter is not provided, the Global object is used as thisObj.

apply method:
Syntax: apply(thisObj, [argArray])
Definition: Apply a method of a certain object and replace the current object with another object.
Note:
If argArray is not a valid array or is not an arguments object, a TypeError will result.
If neither argArray nor thisObj is provided, the Global object will be used as thisObj and no parameters can be passed.

9.b Inherit the method of a

function A( age, name ){ 
this.age = age;
this.name = name;
A.prototype.show = function(){
alert('父级方法');
}
function B(age,name,job){
A.apply( this, arguments );
this.job = job;
B.prototype = new A();
var b = new A(14,'侠客行');
var a = new B(15,'狼侠','侠客');

10.How to prevent event bubbling and default events

canceBubble()只支持IE,return false,stopPropagation()

11.Add delete replace insert to The method of a certain contact point

obj.appendChid() 
obj.insertBefore()
obj.replaceChild()
obj.removeChild()

12.Javascript’s local object, built-in object and host object
The local object is array obj regexp, etc. and can be instantiated with new
The built-in object is gload Math, etc. The
hosts that cannot be instantiated are the document, window, etc. that come with the browser.

13. The difference between window.onload and document ready
window.onload is after the dom document tree is loaded and all After the file is loaded, execute a function Document.ready. The native species does not have this method. There is $().ready(function) in jquery, which executes a function after the dom document tree is loaded (note that the document tree here is loaded does not mean All files have been loaded).
$(document).ready is executed before window.onload. window.onload can only appear once, $(document).ready can appear multiple times

14."==" and "== =”
The former will automatically convert the type, while the latter will not

15.javascript’s same-origin policy
A script can only read the properties of windows and documents from the same source. The same source here refers to the combination of host name, protocol and port number

16. What kind of language is JavaScript and what are its characteristics?
There is no standard answer.
javaScript is a literal scripting language. It is a dynamically typed, weakly typed, prototype-based language with built-in support for types. Its interpreter is called the JavaScript engine, which is part of the browser and is widely used in client-side scripting languages. It was first used on HTML web pages to add dynamic functions to HTML web pages. JavaScript is compatible with the ECMA standard, so it is also called ECMAScript.
Basic features
1. It is an interpreted scripting language (the code is not precompiled).
2. It is mainly used to add interactive behaviors to HTML (an application under Standard Universal Markup Language) pages.
3. It can be directly embedded into HTML pages, but writing it as a separate js file facilitates the separation of structure and behavior.
4. Cross-platform feature, with the support of most browsers, it can run on multiple platforms (such as Windows, Linux, Mac, Android, iOS, etc.).

17.What are the data types of JavaScript?
Basic data types: String, boolean, Number, Undefined, Null
Reference data type: Object(Array,Date,RegExp,Function)
Then the question is, how to determine whether a variable is an array data type ?
Method 1. Determine whether it has "array properties", such as the slice() method. You can define the slice method for this variable yourself, so it sometimes fails.
Method 2.obj instanceof Array is incorrect in some IE versions
Method 3. Both methods 1 and 2 have loopholes, and a new one is defined in ECMA Script5 The method Array.isArray() ensures its compatibility. The best method is as follows:

if(typeof Array.isArray==="undefined")
{
  Array.isArray = function(arg){
        return Object.prototype.toString.call(arg)==="[object Array]"
    }; 
}

18. If you want to get the input value of the input box with a known ID, what should you do? (Do not use third-party framework)

document.getElementById(“ID”).value

19.希望获取到页面中所有的checkbox怎么做?(不使用第三方框架)

var domList = document.getElementsByTagName(‘input’) 
var checkBoxList = []; 
var len = domList.length;  //缓存到局部变量 
while (len--) {  //使用while的效率会比for循环更高 
if (domList[len].type == ‘checkbox’) { 
      checkBoxList.push(domList[len]); 
} 
}

20.设置一个已知ID的DIV的html内容为xxxx,字体颜色设置为黑色(不使用第三方框架)

var dom = document.getElementById(“ID”); 
dom.innerHTML = “xxxx”
dom.style.color = “#000”

21.当一个DOM节点被点击时候,我们希望能够执行一个函数,应该怎么做?
直接在DOM里绑定事件:b28bc9950e24daa5d8431db20bacf9ca94b3e26ee717c64999d7867364b1b4a3
在JS里通过onclick绑定:xxx.onclick = test 
通过事件添加进行绑定:addEventListener(xxx, ‘click’, test) 
那么问题来了,Javascript的事件流模型都有什么? 
“事件冒泡”:事件开始由最具体的元素接受,然后逐级向上传播 
“事件捕捉”:事件由最不具体的节点先接收,然后逐级向下,一直到最具体的 
“DOM事件流”:三个阶段:事件捕捉,目标阶段,事件冒泡

22.看下列代码输出为何?解释原因。
var a;
alert(typeof a); // undefined
alert(b); // 报错
解释:Undefined是一个只有一个值的数据类型,这个值就是“undefined”,在使用var声明变量但并未对其赋值进行初始化时,这个变量的值就是undefined。而b由于未声明将报错。注意未申明的变量和声明了未赋值的是不一样的。

23.看下列代码,输出什么?解释原因。
var a = null; 
alert(typeof a); //object 
解释:null是一个只有一个值的数据类型,这个值就是null。表示一个空指针对象,所以用typeof检测会返回”object”。

24.看下列代码,输出什么?解释原因。

var undefined; 
undefined == null; // true 
1 == true;   // true 
2 == true;   // false 
0 == false;  // true 
0 == '';     // true 
NaN == NaN;  // false 
[] == false; // true 
[] == ![];   // true

undefined与null相等,但不恒等(===) 
一个是number一个是string时,会尝试将string转换为number 
尝试将boolean转换为number,0或1 
尝试将Object转换成number或string,取决于另外一个对比量的类型 
所以,对于0、空字符串的判断,建议使用 “===” 。“===”会先判断两边的值类型,类型不匹配时为false。 
那么问题来了,看下面的代码,输出什么,foo的值为什么? 
var foo = "11"+2-"1"; 
console.log(foo); 
console.log(typeof foo); 
执行完后foo的值为111,foo的类型为String。

25.看代码给答案。

var a = new Object();
a.value = 1;
b = a;
b.value = 2;
alert(a.value);

答案:2(考察引用数据类型细节)

26.已知数组var stringArray = [“This”, “is”, “Baidu”, “Campus”],Alert出”This is Baidu Campus”。
答案:alert(stringArray.join(“”))

27.已知有字符串foo=”get-element-by-id”,写一个function将其转化成驼峰表示法”getElementById”。

function combo(msg){
    var arr=msg.split("-");
    for(var i=1;i<arr.length;i++){
        arr[i]=arr[i].charAt(0).toUpperCase()+arr[i].substr(1,arr[i].length-1);
    }
    msg=arr.join("");
    return msg;
}

(考察基础API)
28.var numberArray = [3,6,2,4,1,5]; (考察基础API)
1) 实现对该数组的倒排,输出[5,1,4,2,6,3] 
numberArray.reverse()
2) 实现对该数组的降序排列,输出[6,5,4,3,2,1]
numberArray.sort(function(a,b){return b-a})

29.输出今天的日期,以YYYY-MM-DD的方式,比如今天是2014年9月26日,则输出2014-09-26
var d = new Date(); 
// 获取年,getFullYear()返回4位的数字
var year = d.getFullYear();
// 获取月,月份比较特殊,0是1月,11是12月
var month = d.getMonth() + 1;
// 变成两位
month = month 3c042d0e6e5459de3fc2dcef52724b93b6c5a531a458a2e790c1fd6421739d1c{$id}b90dd5946f0946207856a8a37f441edfb6c5a531a458a2e790c1fd6421739d1c{$name}b90dd5946f0946207856a8a37f441edffd273fcf5bcad3dfdad3c41bd81ad3e5”中的{$id}替换成10,{$name}替换成Tony (使用正则表达式)
答案:"a34de1251f0d9fe1e645927f19a896e8b6c5a531a458a2e790c1fd6421739d1c{$id}b90dd5946f0946207856a8a37f441edfb6c5a531a458a2e790c1fd6421739d1c{$id}_{$name}b90dd5946f0946207856a8a37f441edffd273fcf5bcad3dfdad3c41bd81ad3e5".replace(/{\$id}/g, '10').replace(/{\$name}/g, 'Tony');

31.为了保证页面输出安全,我们经常需要对一些特殊的字符进行转义,请写一个函数escapeHtml,将95ec6993dc754240360e28e0de8de30a, &, “进行转义

function escapeHtml(str) { 
return str.replace(/[<>”&]/g, function(match) {
    switch (match) {
                   case “<”:
                      return “<”;
                   case “>”:
                      return “>”;
                   case “&”:
                      return “&”;
                   case “\””:
                      return “"”;
      }
  });
}

32.foo = foo||bar ,这行代码是什么意思?为什么要这样写?
答案:if(!foo) foo = bar; //如果foo存在,值不变,否则把bar的值赋给foo。
短路表达式:作为”&&”和”||”操作符的操作数表达式,这些表达式在进行求值时,只要最终的结果已经可以确定是真或假,求值过程便告终止,这称之为短路求值。

33.看下列代码,将会输出什么?(变量声明提升)

var foo = 1; 
(function(){
    console.log(foo);
    var foo = 2;
    console.log(foo);
})()
答案:输出undefined 和 2。上面代码相当于:
var foo = 1;
(function(){
    var foo;
    console.log(foo); //undefined
    foo = 2;
    console.log(foo); // 2; 
  })()

函数声明与变量声明会被JavaScript引擎隐式地提升到当前作用域的顶部,但是只提升名称不会提升赋值部分。

34.用js实现随机选取10–100之间的10个数字,存入一个数组,并排序。

function randomNub(aArray, len, min, max) {
  if (len >= (max - min)) {
  return &#39;超过&#39; + min + &#39;-&#39; + max + &#39;之间的个数范围&#39; + (max - min - 1) + &#39;个的总数&#39;;
  }
  if (aArray.length >= len) {
  aArray.sort(function(a, b) {
  return a - b
  });
  return aArray;
  }
  var nowNub = parseInt(Math.random() * (max - min - 1)) + (min + 1);
  for (var j = 0; j < aArray.length; j++) {
  if (nowNub == aArray[j]) {
  randomNub(aArray, len, min, max);
  return;
  }
  }
  aArray.push(nowNub);
  randomNub(aArray, len, min, max);
  return aArray;
  }
  var arr=[];
  randomNub(arr,10,10,100);

35.把两个数组合并,并删除第二个元素。

var array1 = [&#39;a&#39;,&#39;b&#39;,&#39;c&#39;];
var bArray = [&#39;d&#39;,&#39;e&#39;,&#39;f&#39;];
var cArray = array1.concat(bArray);
cArray.splice(1,1);

36.怎样添加、移除、移动、复制、创建和查找节点(原生JS,实在基础,没细写每一步)
1)创建新节点

createDocumentFragment()    //创建一个DOM片段
createElement()   //创建一个具体的元素
createTextNode()   //创建一个文本节点

2)添加、移除、替换、插入

appendChild()      //添加
removeChild()      //移除
replaceChild()      //替换
insertBefore()      //插入

3)查找

getElementsByTagName()    //通过标签名称
getElementsByName()     //通过元素的Name属性的值
getElementById()        //通过元素Id,唯一性

37.有这样一个URL:,请写一段JS程序提取URL中的各个GET参数(参数名和参数个数不确定),将其按key-value形式返回到一个json结构中,如{a:’1′, b:’2′, c:”, d:’xxx’, e:undefined}。
答案: 

function serilizeUrl(url) { 
var urlObject = {}; 
if (/\?/.test(url)) { 
var urlString = url.substring(url.indexOf("?") + 1); 
var urlArray = urlString.split("&"); 
for (var i = 0, len = urlArray.length; i < len; i++) { 
var urlItem = urlArray[i]; 
var item = urlItem.split("="); 
urlObject[item[0]] = item[1]; 
} 
return urlObject; 
} 
return null; }

38.正则表达式构造函数var reg=new RegExp(“xxx”)与正则表达字面量var reg=//有什么不同?匹配邮箱的正则表达式?
答案:当使用RegExp()构造函数的时候,不仅需要转义引号(即\”表示”),并且还需要双反斜杠(即\\表示一个\)。使用正则表达字面量的效率更高。 
邮箱的正则匹配:

var regMail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((.[a-zA-Z0-9_-]{2,3}){1,2})$/;

39.看下面代码,给出输出结果。

for(var i=1;i<=3;i++){ 
  setTimeout(function(){
      console.log(i);  
    },0); 
};

答案:4 4 4。

原因:Javascript事件处理器在线程空闲之前不会运行。追问,如何让上述代码输出1 2 3?

for(var i=1;i<=3;i++){
   setTimeout((function(a){  //改成立即执行函数
       console.log(a);   
   })(i),0); 
};

40.写一个function,清除字符串前后的空格。(兼容所有浏览器)
使用自带接口trim(),考虑兼容性: 

if (!String.prototype.trim) {
 String.prototype.trim = function() {
 return this.replace(/^\s+/, "").replace(/\s+$/,"");
 }
}
  // test the function
var str = " \t\n test string ".trim();
alert(str == "test string"); // alerts "true"

The above is the detailed content of JS interview questions (must read for interviews). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn