Giter Site home page Giter Site logo

issue-interview's Issues

JavaScript遍历方法for in 和 for of的区别?

  • 遍历数组通常使用for循环,ES5的话也可以使用forEach,ES5具有遍历数组功能的还有map、filter、some、every、reduce、reduceRight等,只不过他们的返回结果不一样。但是使用foreach遍历数组的话,使用break不能中断循环,使用return也不能返回到外层函数。

  • 使用for in 也可以遍历数组,但是会存在以下问题:
    1.index索引为字符串型数字,不能直接进行几何运算
    2.遍历顺序有可能不是按照实际数组的内部顺序
    3.使用for in会遍历数组所有的可枚举属性,包括原型。例如上栗的原型方法method和name属性
    所以for in更适合遍历对象,不要使用for in遍历数组。

  • for in遍历的是数组的索引(即键名),而for of遍历的是数组元素值。for of遍历的只是数组内的元素,而不包括数组的原型属性method和索引name。

  • for in 可以遍历到myObject的原型方法method,如果不想遍历原型方法和属性的话,可以在循环内部判断一下,hasOwnPropery方法可以判断某属性是否是该对象的实例属性。

  • 同样可以通过ES5的Object.keys(myObject)获取对象的实例属性组成的数组,不包括原型方法和属性。

JavaScript的this指向问题?

        <div id="container">container</div>
	<div id="container2">container2</div>
	<div id="container3">container3</div>
	<div id="container4">container4</div>
	<div id="container5">container5</div>
	
	<script type="text/javascript">
		var container = document.getElementById('container'),
			container2 = document.getElementById('container2'),
			container3 = document.getElementById('container3'),
			container4 = document.getElementById('container4'),
			container5 = document.getElementById('container5'),
			innerHTML = '我是Windows的html';
		var events = {
			innerHTML:'我是events',
			getHtml:function () {
				console.log(this.innerHTML)
			},
			setFunc:function () {
				return this.getHtml
			},
			proxy:function () {
				var self = this;
				return function () {
					self.getHtml()
				}
			}
		};
		container.onclick = events.getHtml;//container
		container2.onclick = events.setFunc();//container2
		container3.onclick = events.proxy();//我是events
		container4.onclick = function () {
			window.setTimeout(events.setFunc(),0)//我是Windows的html
		};
		container5.onclick = function () {
			window.setTimeout(events.proxy(),0)//我是events
		};
		window.setTimeout(events.getHtml);//我是Windows的html
		
		container.onclick = events.getHtml.call(events);//我是events
		container.onclick = events.getHtml.bind(events);//我是events
		
	</script>

JavaScript多维数组转一维数组?

方法一:递归

                var arr = [1, [2, [[3, 4], 5], 6]];
		var newArr = [];

		function fun(arr) {
			for(var i = 0; i < arr.length; i++) {
				if(Array.isArray(arr[i])) {
					fun(arr[i]);
				} else {
					newArr.push(arr[i]);
				}
			}
		}
		fun(arr);
		console.log(newArr); //[1, 2, 3, 4, 5, 6]

方法二:使用数组map()方法,对数组中的每一项运行给定函数,返回每次函数调用的结果组成的数组。

                var arr = [1, [2, [3, 4], 5], 6];

		function unid(arr) {
			var arr1 = (arr + '').split(','); //将数组转字符串后再以逗号分隔转为数组
			var arr2 = arr1.map(function(x) {
				return Number(x);
			});
			return arr2;
		}
		console.log(unid(arr));//[1, 2, 3, 4, 5, 6]

方法三:使用apply结合concat,此方法只适用于二维数组。

                var arr = [1, [2, 3], 4];

		console.log([].concat.apply([],arr));//[1, 2, 3, 4]

方法四:reduce+递归

                var arr = [1, [2, [[3, 4], 5], 6]];
		const flatten = arr => arr.reduce(
			(acc, val) => acc.concat(Array.isArray(val) ? flatten(val) : val), []
		)
		console.log(flatten(arr)); //[1, 2, 3, 4, 5, 6]

Vue单页应用添加百度统计?

  • 申请百度统计后,会得到一段JS代码,需要插入到每个网页中去,在Vue.js项目首先想到的可能就是,把统计代码插入到index.html入口文件中,这样就全局插入,每个页面就都有了;这样做就涉及到一个问题,Vue.js项目是单页应用,每次用户浏览网站时,访问内页时页面是不会刷新的,也就意味着不会触发百度统计代码;所以最终在百度统计后台看到的效果就是只统计到了网页入口的流量,却无法统计到内页的访问流量。

  • 解决方法:在main.js文件中调用vue-router的afterEach方法,将统计代码加入到这个方法里面,这样每次router发生改变的时候都会执行一下统计代码,这样就达到了目的。

  • 代码如下:

                  router.afterEach((to, from, next) => {
      		setTimeout(() => {
      			var _hmt = _hmt || [];
      			(function() {
      				//每次执行前,先移除上次插入的代码
      				document.getElementById('baidu_tj') && document.getElementById('baidu_tj').remove();
      				var hm = document.createElement("script");
      				hm.src = "https://hm.baidu.com/hm.js?xxxx";
      				hm.id = "baidu_tj"
      				var s = document.getElementsByTagName("script")[0];
      				s.parentNode.insertBefore(hm, s);
      			})();
      		}, 0);
      	});
    

转自:https://blog.jae.sh/article/v924mq.html

JavaScript的变量提示问题?

                console.log(fn);//undefined
		var fn = () => {};
		var fn;
		console.log(fn);//() => {}
		var fn = 2;
		console.log(fn);//2
		
		var a = 3;
		var	b = 4;
			test = () => {
				console.log(a);//undefined
				console.log(b);//4
				var a = 1;
			};
		test();

JavaScript函数运行的问题?

               (function() {
			try {
				throw new Error();
			} catch(x) {
				var x = 1,
					y = 2;
				console.log(x);//1
			}
			console.log(x);//undefined
			console.log(y);//2
		})();

JavaScript怎么判断对象是不是数组?

方法一:从原型入手,Array.prototype.isPrototypeOf(obj);利用isPrototypeOf()方法,判定Array是不是在obj的原型链中,如果是,则返回true,否则false。

                console.log(Array.prototype.isPrototypeOf([]));//true
		console.log(Array.prototype.isPrototypeOf({}));//false

方法二:从构造函数入手,obj instanceof Array。

                console.log([] instanceof Array)//true
		console.log({} instanceof Array);//false

方法三:根据对象的class属性(类属性),跨原型链调用toString()方法。

                console.log(Object.prototype.toString.call([]));//[object Array]
		console.log(Object.prototype.toString.call({}));//[object Object]
		console.log(Object.prototype.toString.call(null));//[object Null]
		console.log(Object.prototype.toString.call(new Date()));//[object Date]
		console.log(Object.prototype.toString.call(window));//[object Window]
		console.log(Object.prototype.toString.call(/./));//[object RegExp]

方法四:Array.isArray()方法。

                console.log(Array.isArray([1, 2, 3])); // true
		console.log(Array.isArray({
			foo: 123
		})); // false
		console.log(Array.isArray('foobar')); // false
		console.log(Array.isArray(undefined)); // false

JavaScript原型链问题?

                var name = 'opp';
		var Person = function (options) {
			this.name = options.name
		};
		Person.prototype.name = 'Person';
		Person.prototype.getName = function () {
			return this.name;
		};
		var p = new Person({name:'inke'});
		
		console.log(p.constructor === Person);//true
		console.log(p instanceof Person);//true
		console.log(p.__proto__ === Object);//false
		console.log(p.hasOwnProperty('name'));//true
		console.log(p.hasOwnProperty('getName'));//false
		
		var getName = p.getName;
		
		console.log(getName === Person.prototype.getName);//true
		console.log(getName());//opp
		console.log(Person.prototype.getName());//Person
		console.log(p.getName());//inke

JavaScript函数参数的派发和作用域?

              var MAP = {
			onclick:function  () {
				
			},
			curry:function (val) {
				return function (z) {
					return val++ + z;
					console.log(val)
				}
			}
		};
		var getInfo = function (val) {
			return MAP[val]
		};
		var fn = getInfo('curry');
		var a = fn(100);
		console.log(a(200));//300
		console.log(a(300));//401
		console.log(fn(100)(200));//300
		console.log(getInfo('curry')(100)(300));//400

JavaScript的普通类型和对象类型?

                var obj = {
			name:'baidu',
			arr:['a','b','c']
		};
		var obj2 = obj;
		obj2.arr = ['a','b','c','d'];
		obj2.name = 'inke';
		console.log(obj2.arr);//['a','b','c','d']
		console.log(obj.arr);//['a','b','c','d']
		console.log(obj.name);//'inke'
		console.log(obj === obj2);//true
		console.log(obj.arr === obj2.arr);//true

JavaScript将对象快速转化为URL参数?

                 /** 
		 * param 将要转为URL参数字符串的对象 
		 * key URL参数字符串的前缀 
		 * encode true/false 是否进行URL编码,默认为true 
		 *  
		 * return URL参数字符串 
		 */
		var urlEncode = function(param, key, encode) {
			if(param == null) return '';
			var paramStr = '';
			var t = typeof(param);
			if(t == 'string' || t == 'number' || t == 'boolean') {
				paramStr += '&' + key + '=' + ((encode == null || encode) ? encodeURIComponent(param) : param);
			} else {
				for(var i in param) {
					var k = key == null ? i : key + (param instanceof Array ? '[' + i + ']' : '.' + i);
					paramStr += urlEncode(param[i], k, encode);
				}
			}
			return paramStr;
		};

		var obj = {
			name: 'tom',
			'class': {
				className: 'class1'
			},
			classMates: [{
				name: 'lily'
			}]
		};
		console.log(urlEncode(obj));
		//output: &name=tom&class.className=class1&classMates[0].name=lily  
		console.log(urlEncode(obj, 'stu'));
		//output: &stu.name=tom&stu.class.className=class1&stu.classMates[0].name=lily

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.