javascript tips and snippets
如何给javascript对象动态创建动态key
// ES2015
var key = 'DYNAMIC_KEY',
obj = {
[key]: 'ES6!'
}; console.log(obj);
// > { 'DYNAMIC_KEY': 'ES6!' } // NON ES2015
var obj = [];
obj[] = "hello world";
obj["something"] = ; var objJSON = JSON.stringify(obj);
数字化的Date
js中,Date是内置的一种数据类型,虽然直接输出的date格式适合人们阅读,但是对于机器程序来说却有些不方便:
var now=new Date();
console.log(now);//Wed Nov 25 2015 22:02:17 GMT+0800 (中国标准时间)
怎么转换为便于js程序来操作的形式呢?很简单只要在new关键字前面加上一个+即可:
var now=+new Date();
console.log(now);//
javascript Errors: try{}catch(){}的重要性
在JS APP中,对于一些很有可能会出错的代码,强烈建议使用try{}catch(){}的方式来调用,否则会出现一个错误就导致app crash的问题。相信crash并不是你想要的状态,你可能希望出错没有关系啊,下次出错的条件解除了,我们希望程序能够继续运行,这就必须使用try catch的模式来写可能出错的代码,允许出错
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error
try {
foo.bar();
} catch (e) {
if (e instanceof EvalError) {
alert(e.name + ': ' + e.message);
} else if (e instanceof RangeError) {
alert(e.name + ': ' + e.message);
} else if (e instanceof InternalError) {
alert(e.name + ': ' + e.message);
}else if (e instanceof ReferenceError) {
alert(e.name + ': ' + e.message);
}else if (e instanceof SyntaxError) {
alert(e.name + ': ' + e.message);
}else if (e instanceof TypeError) {
alert(e.name + ': ' + e.message);
}else if (e instanceof URIError) {
alert(e.name + ': ' + e.message);
}
// ... etc
}
Javascript小数点问题
由于javascript使用浮点数来运算小数,而小数总归会有一定的精确度,所以往往出现一些比较怪异的问题:
console.log(0.1+0.2);//0.30000000000000004
console.log((0.1+0.2).toFixed(2));//0.30
(0.1+0.2)==0.3 //false!!!!
(0.1+0.2).toFixed(1)==0.3 //true!!!
(0.1+0.2).toFixed(2)===0.3 //flase!!! 原因是toFixed(2)调用后实际上返回的是"0.30"
在上面的代码,由于toFixed将返回一个字符串,所以使用===来比较,则返回false;再看下面的代码:
function tax(price,percent){
return parseFloat((price*percent/100).toFixed(2));
}
var myprice = 9;
var taxpercent =70;
var total = myprice+tax(myprice,taxpercent);
console.log(total.toFixed(2)); //"15.30"
javascript hoisting
<!DOCTYPE html>
<html>
<body> <p id="demo"></p> <script>
var x = 5; // Initialize x elem = document.getElementById("demo"); // Find an element
elem.innerHTML = "x is " + x + " and y is " + y; // Display x and y==> x is 5 and y is undefined,虽然y是declared了(due to hoisting),但是却没有defination未定义 var y = 7; // Initialize y
</script> </body>
</html>
modula Pattern
var ARMORY =(function(){
var weaponList = [*list of weapon objects*];
var armorList = [*list of armor objects*]; var removeWeapon = function(){};
var replaceWeapon = function(){};
var removeArmor = function(){};
var replaceArmor = function(){}; return {
makeWeaponRequest: function(){};
makeArmorRequest: function(){};
}; })();
ARMORY.makeWeaponRequest('Excalibur');
上面这段代码中,使用IIFE调用后返回一个global object ARMORY作为namespace,暴露两个public函数公外部调用,内部的local data都已经被封装起来,
通过ARMORY.makeWeaponRequest()函数调用,来通过private函数removeWeapon又去访问namespace的local variable weapList,删除相应武器数据后,可能返回一个weapon列表对象的copy到ARMORY.makeWeaponRequest的scope中去使用。
Import Globals into IIFE
在上面的module pattern中,如果需要访问一个全局变量,比如我们添加一个指示是否正在战争游戏的flag,在makeWeaponRequest函数中,我们根据这个flag来做特定的动作,那么可行的方法是将wartime这个flag作为IIFE的参数传入:
var wartime = true;
var ARMORY =(function(war){
var weaponList = [*list of weapon objects*];
var armorList = [*list of armor objects*]; var removeWeapon = function(){};
var replaceWeapon = function(){};
var removeArmor = function(){};
var replaceArmor = function(){}; return {
makeWeaponRequest: function(){
if(war) //let civilians have weaponry };
makeArmorRequest: function(){};
}; })(wartime);
ARMORY.makeWeaponRequest('Excalibur');
在上面这个pattern中,需要注意的是wartime作为参数传入了IIFE虽然意味着IIFE中能够方便的访问到wartime的数据拷贝,但是如果外部的环境发生变化了,后续再调用makeWeaponRequest时,无法感知!@!原因是war这里是wartime的一个copy,并不是直接引用!
当然,如果希望内部和外部完全同步,有一个可行的方法是,将wartime声明为一个object或者array,在IIFE内部通过 object.property,array[index]方式来读或者写就可以实现内外完全同步了!看下面的简单说明:
function replace(ref) {
ref = {}; // this code does _not_ affect the object passed
} function update(ref) {
ref.key = 'newvalue'; // this code _does_ affect the _contents_ of the object
} var a = { key: 'value' };
replace(a); // a still has its original value - it's unmodfied
update(a); // the _contents_ of 'a' are changed
文字盒翻滚效果
var wordBox = $("#theWords");
var timer; timer = setTimeout(function(){ var argCallee = arguments.callee; var fSpan = $("#theWords span:first"); fSpan.animate({
marginTop:-20
},500,function(){
wordBox.append(fSpan);
fSpan.css("margin-top","0");
timer = setTimeout(argCallee,3000);
}); },3000);
html:
<div id="theWords" class="theScrollword"> <span style="margin-top: 0px;">不怕做不到只怕想不到。</span><span style="margin-top: 0px;">学而不思则罔!</span><span style="margin-top: 0px;">思而不学则殆 </span><span style="margin-top: 0px;">我听我忘,我看我会,我做我懂 </span><span style="margin-top: 0px;">做个有价值的人。</span></div>
css:
.theScrollword {
height: 20px;
overflow: hidden;
position: relative;
margin: 20px 0 0;
padding: 0 0 0 40px;
float: left;
display: inline;
}
.container .toparea .notice span {
text-align: left;
color: #fffeff;
font-size: 14px;
display: block;
}
上面一段代码的原理是使用jquery的animate函数对第一个span的margin-top属性来做动画,并且不断将第一个span移动到最后去
jquery document ready and window load
我们知道javascript在操作一个页面的元素时,必须保证document is "ready"。 jQuery侦测readiness状态。在$(document).ready()函数中的代码只有在页面的Document Object Model(DOM)完全就绪后才会被执行(而对于未定义在ready handler中的javascript代码则基本上会在DOM完全构建完成之前运行!!!)。而在$(window).load(function(){...})中的代码则只有整个page的资源(images,css,iframes)都加载完成(或者timeout failure)后才被运行,而不是DOM一就绪就运行;
DOM就绪发生在HTML Document被浏览器接收(注意对应的JS也被加载运行了!!),并且解析成对应的DOM数后发生!。看看下面的示例代码:
<html>
<head>
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$( document ).ready(function() {
console.log( "document loaded" );
}); $( window ).load(function() {
console.log( "window loaded" );
});
</script>
</head>
<body>
<img src="http://xx.yy.com/build/images/internet.jpg" />
<iframe src="http://techcrunch.com"></iframe>
</body>
</html>
上面的代码将首先打出“document loaded”,随后在img,iframe全部加载完成后,打印出"window loaded"
列出所有全局空间的对象
有时我们希望看到在我们的页面上有哪些可以操作的全局对象,通过Object.keys(window)就可以轻松实现。更进一步,我们希望打印出对象,并且方便检视,则可以使用下面的代码:
(function ()
{
var keys=Object.keys( window );
for (var i in keys)
{
if (typeof window[keys[i]] != 'function')
console.log(keys[i], window[keys[i]]);
}
})();
函数柯里化充分理解闭包,返回函数的概念
function add(value) {
var helper = function(next) {
console.log("value is: "+ value + "--line 481" );
value = typeof(value)==="undefined"?next:value+next;
console.log("value is: " +value + "--line 483");
return helper;
}
helper.valueOf = function() {
console.log("valueOf is called at 488");
return value;
}
return helper;
}
console.log(add(2)(3)(5)(7));
value is: 2--line 481
value is: 5--line 483
value is: 5--line 481
value is: 10--line 483
value is: 10--line 481
value is: 17--line 483
jstext.html:495 17
valueOf is called at 488
注意:valueOf是console.log(returnHelper)时js引擎自动会调用returnHelper.valueOf方法的~~~!
如何reset input file控件的选择状态以便能够再次选择同一文件?
input file控件在首次选择文件后,如果我们取消remove掉了所选文件,后面突然反悔又希望再次选中同一个文件,由于该控件具有一个内在的逻辑是由于选过,不允许重复选择,因此选择无效,这时,一个简单有效的方法是通过javascript设置该空间的type属性
input.type = ''
input.type = 'file'
javascript中的数组操作方法
在javascript中对数组的操作总体上分为两类:一种是mutation的也就是执行对应函数后原数组将会被修改,一种是accessor,就是返回源数组的部分数据,不会对原数组做任何的修改。
mutation类的函数有:
array.reverse, array.splice, array.shift, array.unshift, array.sort
accessor类的函数有
array.concat, array.indexOf, array.join, array.lastIndexOf, array.slice
javascript regex正则
https://javascript.info/regexp-methods
javascript tips and snippets的更多相关文章
- 45 Useful JavaScript Tips, Tricks and Best Practices(有用的JavaScript技巧,技巧和最佳实践)
As you know, JavaScript is the number one programming language in the world, the language of the web ...
- 转:45 Useful JavaScript Tips, Tricks and Best Practices
原文来自于:http://flippinawesome.org/2013/12/23/45-useful-javascript-tips-tricks-and-best-practices/ 1 – ...
- 45 Useful JavaScript Tips, Tricks and Best Practices
<45 Useful JavaScript Tips, Tricks and Best Practices> http://flippinawesome.org/2013/12/23/45 ...
- JavaScript Tips
Tips: return false - event.preventDefault(); //阻止默认行为 P.S 阻止a标签的跳转 - event.stopPropagation(); //阻止事件 ...
- JavaScript tips —— target与currentTarget的区别
定义 以下是红宝书的描述 属性/方法 类型 读/写 说明 currentTarget Element 只读 其事件处理程序当前正在处理事件的那个元素 target Element 只读 事件的目标 M ...
- JavaScript tips:数组去重
1.实现目标:数组去重 2.实现思路: (1)创建新数组. (2)遍历原数组,判断当前被遍历元素是否存在于新数组,如果存在于新数组,则判断当前被遍历元素是重复的:如果不存在于新数组,则判断当前被遍历元 ...
- JavaScript tips ——搞定闰年
前言 处理时间时,常常要考虑用户的输入是否合法,其中一个很典型的场景就是平闰年的判断,网上其实有很多类似的算法,但是其实不必那么麻烦,下面我讲讲的我的思路. 规则 公元年数可被4整除为闰年,但是整百( ...
- javaScript tips —— z-index 对事件机制的影响
demo // DOM结构 class App extends React.Component { componentDidMount() { const div1 = document.getEle ...
- javaScript tips —— 标签上的data属性
HTML5规定可以为元素添加非标准型的属性,只需添加前缀data-,这些属性可以随意添加,随意命名,目的是为元素提供与渲染无关的信息,或提供语义信息. 传统获取方式 'getAttribute' da ...
随机推荐
- android 企业级高性能图表库 SciChart (付费)
1.官网 https://www.scichart.com/ 2.特性 2.1 链接 https://www.scichart.com/android-chart-features/ https:// ...
- VUE安装步骤1
文件结构 用官方的 vue-cli 生成的项目文件结构如上图所示,简单介绍下上面图中各文件的作用. src 文件夹 : 1. assets 文件夹:存放各种资源文件,如图片等 2. component ...
- RT-Thread Nano移植
RT_Thread移植:在MDK下以组件形式提供 https://pan.baidu.com/s/1miac86O#list/path=%2Fsharelink4264488348-377157516 ...
- PyCharm | 常见问题
1.安装使用 每次建立PyCharm工程都建立一个虚拟环境env,需要重新下载或复制模块
- (转)python之os,sys模块详解
python之sys模块详解 原文:http://www.cnblogs.com/cherishry/p/5725184.html sys模块功能多,我们这里介绍一些比较实用的功能,相信你会喜欢的,和 ...
- selenium+Python(cookie处理)
cookie 处理本节重点: driver.get_cookies() 获得 cookie 信息 add_cookie(cookie_dict) 向 cookie 添加会话信息 delete_cook ...
- java gc 随记
gc为garbage collection的缩写,中文翻译为垃圾回收.垃圾为不在使用的实例.变量,回收为释放垃圾所占用的内存空间. 学习过的C语言.C++语言,是没有垃圾回收机制的,因此需要软件工程师 ...
- 全面理解面向对象的JavaScript
转载:http://justcoding.iteye.com/blog/2019293 原文:http://www.ibm.com/developerworks/cn/web/1304_zengyz_ ...
- MySql 学习(一)
入门使用 show databases; //假设存在seckill 数据库 use seckill; //查看所有表 show tables; //查看某个表的字段,例如存在 student 表 d ...
- java.lang.RuntimeException: Canvas: trying to draw too large(107331840bytes) bitmap.
环境: Android 8.0.1 MIUI 真机测试闪退 gradle 4.1 compileSdkVersion 26 buildToolsVersion '26.0.2' minSdkVersi ...